Reputation: 5559
I have the following 2 links which are formed in a ruby rails .each do block:
<%= link_to "Reply", '#', class: 'reply-link', id: "reply-#{sender}" %>
<%= link_to "Resolved", '#', class: 'complete-link', id: "resolved-#{sender}" %>
I want to be able to do something like this but I'm not sure how to extract the rails record id (#{sender}) in the ajax post.
$('.reply-link').click(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: '/messages/complete?sender='+$(this).attr("id")
});
});
The $(this).attr("id")
above obviously returns reply-1
instead of 1
Upvotes: 0
Views: 404
Reputation: 9958
try this,
$('.reply-link').click(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: '/messages/complete?sender='+$(this).attr("id").split("-")[1]
});
});
Upvotes: -1
Reputation: 3356
$(this).attr("id")
is returning correct id "reply-1"
for the element. But you need number out of that id attribute, so do the following:--
$(this).attr("id").split("-")[1]
Upvotes: 0
Reputation: 887
You can use a data-* attribute as well, if it fits your needs:
<%= link_to "Reply", '#', class: 'reply-link', data: { id: sender } %>
<%= link_to "Resolved", '#', class: 'complete-link', data: { id: sender } %>
You can then use
$('.reply-link').data('id')
$('.resolved-link').data('id')
which is cleaner instead of putting "reply-" and "resolved-" strings in the id attribute and then having to do string manipulations.
Upvotes: 2
Reputation: 3939
You can use the split
method to get your id
like so:
$(this).attr("id").split("-")[1];
But a cleaner and better solution would be to go for the data
attribute. In this case, you would store the id
like this:
<%= link_to "Reply", '#', class: 'reply-link', data-id: sender %>
You can retrieve this with the data
method:
var id = $(this).data("id");
An added advantage of this is the fact that data
attributes get cached by JQuery
.
Upvotes: 0
Reputation: 148110
You are getting the correct id, if you need number then need to remove string reply-
from the id.
$(this).attr("id").replace("reply-", "");
Upvotes: 0