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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With