Reputation: 2227
I have one Controller VendorController
. And view file is index.html.erb
I want to pass the id of vendor through onclick function. Here is my code
Codes under vendors_controller.rb
def index
@vendor = Vendor.all
end
Codes of index.html.erb
<script language="javascript" type="text/javascript">
function func1(id) {
alert(_id);
}
function func2(id) {
alert(id);
}
</script>
<% @vendors.each do |vendor| %>
<tr>
<td><%=link_to vendor.name , '#', onclick: "func1(1)", remote: true %></td>
<td><%= link_to vendor.id, '#', :onclick => 'func2(vendor.id)' %></td>
</tr>
<% end %>
For func1()
i am getting the alert. But for func2
I am not getting any response.
Please help..thank you in advance.
Upvotes: 3
Views: 6154
Reputation: 1013
@max-williams answer should solve your problem. But I'd also recommend that you explore the option of embedding the record ID in the <tr>
tag as a data attribute instead of writing out the onclick
function. Then in your JS, you can dynamically select the ID in your event listeners.
Consider:
<tr data-id="<%= vendor.id %>">
<td><%= link_to vendor.id, '#', :class=>"vendor-link" %></td>
</tr>
Then just listen for clicks:
$( ".vendor-link" ).click(function() {
id = $(this).closest("tr").data("id");
alert(id);
});
This method will separate out your JS from your HTML template and make it a little more manageable. Plus, you can also attach multiple click functions, giving you a little more flexibility.
Upvotes: 10
Reputation: 32955
I think you just need to escape the contents of your onclick to have the actual id in it, instead of just a string saying "vendor.id" - remember it's just a string, so it needs to have the right data in it when it gets loaded in the browser.
Try
<td><%= link_to vendor.id, '#', :onclick => "func2(#{vendor.id})" %></td>
Note double quotes, to allow string interpolation.
Upvotes: 3