Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  194] [ 2]  / answers: 1 / hits: 54413  / 9 Years ago, fri, may 22, 2015, 12:00:00

I have a list of entries generated by PHP, each in its own div and each with a unique ID. I'm trying to develop an AJAX call that can remove each entry based on their ID, however whenever I run the script below, it always returns 0.


<div>
Some entry here
<button id="0" class="remove">Remove</button>
</div>
<div>
Another entry here
<button id="1" class="remove">Remove</button>
</div>
// ... and so on

<script>
$(".remove").click(function() {
var id = $(".remove").attr('id');
alert(id); // debug
// AJAX call here
});
</script>

Previously I tried the same thing except for the other way around - the id returned by PHP was in the class attribute and the id attribute had the value 'remove' and this only returned 0 for the first button. The second button didn't invoke the jQuery script at all.


How can I pass a unique ID to the same jQuery call?


More From » jquery

 Answers
61

Try this



$(.remove).click(function() {
var id = $(this).attr('id'); // $(this) refers to button that was clicked
alert(id);
});

[#66504] Wednesday, May 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alvin

Total Points: 55
Total Questions: 101
Total Answers: 109

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;