1

I have an edit button inside td that when clicked opens a modal. The form in the modal body loads from an external file. I'd like to pass the row id value to the form. In my attempt, the id isn't passed on the very first click(it returns undefined) but on the subsequent ones it works perfectly fine.

Here's the html code:

 <button type="button" class="btn" id="edit" 
data-id="<?php echo $row['id'] ;?>"></button>

Script:

  $(document).ready(function() {
        $("#tableCountries tbody tr td button.btn").on("click", function() {
            if ($(this).attr("id") == "edit") {
                //fetch row id from button
                var rowid = $(this).data('id');
                //open modal
                var modal = $("#modalCountries").modal();
                //load external form into modal body
                modal.find('.modal-body').load("modal.html #countries_form");
                //add row id value to countries form
                $("#countries_form").attr('data-value', rowid);
                //check value of id
                var newid = $("#countries_form").data('value');
                alert(newid);
             }
        });
    });

I've tried using bind() or live() instead of on(), I've tried using data() instead of attr() to assign id, I've also tried putting load() outside the if statement. None of it works. Any help would be appreciated.

1 Answer 1

1

.load() is asynchronous so you'll have to use its callback to run code after it finishes.

modal.find('.modal-body').load("modal.html #countries_form", function(){
    $("#countries_form").attr('data-value', rowid);
});
Sign up to request clarification or add additional context in comments.

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.