1

I have a bootstrap modal I use for a deletion confirmation. After I submit a entry delete it will not work again until I reload the page. I am using javascript to watch for button click. The id attribute is passed to another function and submitted via ajax. The data-id attribute it not updated and still has the old button data-id.

I am not sure how to make the id attribute reset without reloading the page. Any help is appreciated. Sorry new to coding.

Here is the Button Code: <button type="button" data-toggle="modal" data-target="#confirm_delete_modal" name="delete_btn" id="' + clockData.id + '" class="btn btn-xs btn-danger btn_delete"></button>

Here is the JS:

//Trigger Delete Confirmation Modal
$(document).on('click', '.btn_delete', function () {
  var id = $(this).attr('id');
 $('#delete_confirm').attr('id', id); //set the data attribute on the modal button

});

// Trigger Ajax delete function
$('#delete_confirm').click(function(){
var id = $(this).attr('id');

    $.ajax({
            url: "/clock/delete",
            method: "POST",
            data: {id: id},
            success: function (data) {

                $('#confirm_delete_modal').modal('hide');
                search_data();

            }
        })
});

2 Answers 2

2

After the first run, the id attribute of the (previously) #delete_confirm button is actually changing, since you're resetting it via $('#delete_confirm').attr('id', id);. When the .btn_delete handler runs a second time, there is no #delete_confirm to change the id of, since it is now the id from the first delete button click.

The best solution with your implementation would be to use the data-id attribute, instead of the actual id for tracking which delete button was clicked.

$(document).on('click', '.btn_delete', function () {
  var id = $(this).attr('id');
 $('#delete_confirm').data('id', id); //set the data attribute on the modal button
});

// Trigger Ajax delete function
$('#delete_confirm').click(function(){
  var id = $(this).data('id');

  $.ajax({
    url: "/clock/delete",
    method: "POST",
    data: {id: id},
    success: function (data) {

      $('#confirm_delete_modal').modal('hide');
      search_data();

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

Comments

1

Use data('id') to get attribute data-id

$(document).on('click', '.btn_delete', function () { var id = $(this).data('id'); // $('#delete_confirm').attr('id', id); });

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.