0

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

1
  • link_to "Reply", '#', class: 'reply-link', id: "reply-#{sender}" you're setting the id to "reply-number"? Commented Feb 13, 2014 at 7:43

5 Answers 5

2

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.

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

Comments

0

You are getting the correct id, if you need number then need to remove string reply- from the id.

$(this).attr("id").replace("reply-", "");

1 Comment

Thanks @RUJordan, so nice of you.
0

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.

Comments

0
$(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]

Comments

-1

try this,

$('.reply-link').click(function(event) {
 event.preventDefault();
  $.ajax({
  type: 'POST',
  url: '/messages/complete?sender='+$(this).attr("id").split("-")[1]
 });
});

2 Comments

$(this).attr("id").split("reply-")[1] will give you the id e.g: for "reply-1" it will give you "1".
Yes you are right. It will work. But its not the ideal usage of the split function.

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.