0

I am having trouble with passing the correct data from my rails html.erb view file to my js file.

I have the following in my controller (@messages = Message.all) and in my html.erb view file:

@messages.each do |x|
x.name
end

if i have a javscript file how do i pass the id of the specific message to it?

I am trying this:

@messages.each do |x|
<span id="messageid" data-id="<%= x.id %>">
 <%=x.name%>
</span>
end

and in my javascript file:

$("#messageemail").click(function(){
  var messageid = $("#messageemail").data('id');
alert(messageid);

this partially works, but it only gives me the id for the first message in the list. I want it to give me the specific id of which ever message is clicked

1
  • Where is element with messageemail id? Commented Jul 16, 2015 at 6:46

2 Answers 2

2

Do this instead, add a class to your span element instead of id

<span class="message-class" data-id="<%= x.id %>">

In Javascript file

$(".message-class").on('click', function(){
  var messageid = $(this).attr("data-id");
  alert(messageid);
});

This will work!

Sign up to request clarification or add additional context in comments.

Comments

-1

In your rails view:

<span  onclick="callJS(<%= x.id %>)">
 <%=x.name%>
</span>

Here on clicking the span the callJS function will be called.

in the js :

// in your js file
 function callJS(x_id){
  console.log(x_id);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.