Sunday, January 17, 2016

Passing and Retrieving Data from Booststrap Modal

Recently in one my project I was using a theme which is using boostrap modal. Basically I was using modal for confirmation of delete and once user click on confirm process the delete action. I was using laravel REST API so we have to pass the id of object to be destroyed. So I have to pass id of object to modal and confirmation call API to delete. In this blog I will explain how to do this.

First of all add following modal code to your HTML.

<div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h4 class="modal-title">Confirmation</h4>
            </div>
            <div class="modal-body">
                <p> Are you sure you want to delete? </p>
                <input type="hidden" id="objectId"/>
            </div>
            <div class="modal-footer">
                <button type="button" data-dismiss="modal" class="btn dark btn-outline">Cancel</button>
                <button id="confirmDelete" type="button" data-dismiss="modal" class="btn green">Continue</button>
            </div>
        </div>
    </div>

As you can in above code I have added one hidden field in modal where we will store object id.

Now following will your code of delete button.

<a id="deleteButton" data-id="{{$object->id}}" data-toggle="modal" href="#deleteConfirmation" class="btn btn-danger btn-sm">

As soon as you click on delete button modal will be displayed.

Now add following code to your JavaScript.

    $(document).on("click", "#deleteButton", function () {
        var id = $(this).data('id');
        jQuery('#deleteConfirmation .modal-body #objectId').val( id );
    });

    $('#deleteConfirmation .modal-footer button').on('click', function (e) {
        var $target = $(e.target); // Clicked button element
        $(this).closest('.modal').on('hidden.bs.modal', function () {
            if($target[0].id == 'confirmDelete'){
                $id = $('#deleteConfirmation .modal-body #objectId').val();
            }
        });
    });

As you can in above code we have added click event on delete button and setting id in modal hidden field.

Then we are adding event for confirm button in modal window and getting value stored in hidden field and then you can call the APIs or submit form whatever you want.

Hope this helps you.

No comments:

Post a Comment