Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  173] [ 2]  / answers: 1 / hits: 21760  / 8 Years ago, sat, june 11, 2016, 12:00:00

I am creating a delete comment function and
this are the pieces of html for a delete comment functionality.



<div id=comment-area>
<div class=list-border>
<small class=mdl-button delete-comment js-delete-comment pull-right data-url=http://myproject.com/comment_controller/delete_comment/12/6>
x
</small>
</div>
<div class=list-border>
<small class=mdl-button delete-comment js-delete-comment pull-right data-url=http://myproject.com/comment_controller/delete_comment/13/6>
x
</small>
</div>
</div>


And this is the function for delete a comment, which is automatically loaded when document is ready,



function delete_comment () {
$('.delete-comment').click( function (e) {
var url = $('.delete-comment').attr('data-url');
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (data) {
$('#comment-area').html(data.comments);
delete_comment();
},
error: function () {
alert('error');
}
});
});
}


The problem with this function from the given html above, if I'm going to click on .delete-comment with
data-url=http://myproject.com/comment_controller/delete_comment/13/6 take note on this 13/6, the javascript function delete_comment(),
in this line



var url = $('.delete-comment').attr('data-url');



chose to get the data-url=http://myproject.com/comment_controller/delete_comment/12/6 take note also this 12/6, to see the difference, instead of the data-url of .delete-comment I clicked.



In short, this function always chose the first-child div small, whatever small.delete-comment I'm going to click.



What was the best solution for this?


More From » jquery

 Answers
21

Try



var url = $(this).attr('data-url');


You are getting the attribue value by className and multiple elements have same class so the attribute value for first element found in dom is being returned.



So you need to get the value of element which is clicked and you can use this to get the value of clicked element.


[#61810] Thursday, June 9, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronans

Total Points: 460
Total Questions: 109
Total Answers: 108

Location: Slovenia
Member since Sat, Sep 11, 2021
3 Years ago
;