4

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?

2 Answers 2

13

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.

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

Comments

2

A more robust way to approach this would be to use the jQuery .data() function.

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

This will pick up any dynamically added/updated url that may have changed via JavaScript, but not updated in the DOM attribute.

Comments

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.