Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the data-url correctly using javascript function

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?

like image 366
Fil Avatar asked Dec 15 '22 05:12

Fil


1 Answers

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.

like image 113
Mairaj Ahmad Avatar answered Dec 21 '22 11:12

Mairaj Ahmad