92

Bootstrap 3 – One Delete Confirm Dialog For All

There is no need for a brief about twitter bootstrap, we all (web developers) know what is it and we also know the benefits for using the twitter bootstrap in any project. Recently version - 3 of twitter bootstrap has been released and there are some changes has been made in the new version and added some new features as well. If you want to read more about twitter bootstrap - 3 then visit the bootstrap’s website.

In bootstrap there is a component known as modal dialog which is a very useful (everything is useful tho) thing and most often used in a web application with rich user interface to show the user a confirmation dialog with two choices, for example, if a button click action deletes a record from the database then developer may want to show a confirmation to the user so user can chose an option by clicking on a button and this is still possible without bootstrap but use of bootstrap brings extra dignity to any website because of it’s awesome user interface with eye-caching colorful control elements and fancy icons. Anyways, I’m not talking more about this but going to the main topic and it’s how to use one modal dialog for any/every delete confirmation of the application with different confirmation messages.

How to integrate only one twitter bootstrap modal dialog as confirmation dialog for multiple action buttons!

Step – 1

First of all, you need to add bootstrap.css file using a link tag, jQuery and bootstrap.js file using a script tag in your head section of your web page. On bootstrap’s website, you would find details about this. It’s also possible to build a customized file with selected components from here if you don’t want to use full bootstrap framework.

Step – 2

Add following html code in a file and save it as a separate file, for example delete_confirm.php (I’m using PHP in this example)

Also, paste following JavaScript code in the same file as well

Step – 3

Now, in any page where you want to use this confirm modal dialog, just include it using require_once or include_once like:

Step – 4

To build a delete action button we may use something like this:

That’s it. If we click on delete button then a conform dialog should appear and clicking on Cancel button the modal will be closed and clicking on delete button, the form will be submitted to the target action of the form. Here data-target="#confirmDelete" refers to the modal dialog which is hidden by default and will be prompted by clicking on the delete button because of data-toggle="modal", also notice the data-title="Delete User", this will be set as the title of the dialog and definitely you can change it according to your action and data-message="Are you sure you want to delete this user ?" is the message that will be appeared in the dialog as a confirmation message and here I’m using this for deleting a user so it’s set accordingly. That’s all.

The work flow is very simple, just create a single file for the confirm dialog and put html and js code in that file then include this file at the end of your main file on which you have a delete or something like this which requires a confirmation and add the required data-attributes to the submit button of the form with a title and a message or just leave it to the default and you are done.

In one of my Laravel Projects I’ve used this implementation for every delete confirm action like this:

This is it. In every blade view file, if I need the confirmation then I just include it at the bottom of my view and in this main view I just set the data-title and data-message attributes in the submit button of the delete form and I’m done for the delete confirmation modal dialog.

This is an screenshot of my working project using this approach:

del_conf

 

Update (25-09-2014 01:06 AM Asia/Dhaka):

This is another way to do it using a link, for example, <a href="">Delete</a> instead of a form. Recently I’ve implemented this approach in one of my projects where I’ve use bootstrap-3 and Button Group, which looks like this:

confirm_delete

For this, I’ve used following HTML in a separate file which was included using @include('filename') at the bottom of my View:

Also in that file, I had a script tag which was the required JavaScritp code for this to work and that is given below:

In my main view, I’ve used following code to generate four actions such as View, edit, Suspend and Delete in a Button Group:

Since the delete action was not allowed using a GET but DELETE in my application so I’ve used a hidden form to achieve this but it’s also possible using it without a form if needed and anyone can achieve this by making a little change in the JavaScript code. Hope it helps.

  • dejan_wdp

    Line 12 type=’submit’ should be type=’button’ or the form will be submitted when clicking on the Delete button

    • @dejan_wdp:disqus, No it’s fine and won’t be submitted because Bootstrap handles the click/submission.

      • Brian

        Not sure about that… type=’submit’ would not work for me. It would submit before I even had a chance to select yes/no. Changed to type=’button’ and it works just fine.

        • Not sure but it works on my project and it was copied from that.

        • rainhanifa

          i’ve tried both ‘submit’ and ‘button’ but the form still submitted when clicking delete 😐

          • Check for any JavaScript errors on your browser’s console.

  • rod_vlp

    my form its submitted when i click in the delete button, i see the modal window appearing and disapearing…

    • Make sure you have configured your button properly with all data- attributes and you have no JavaScript errors in browser’s console.

  • XanderTheCoder

    First thank you for this great example! Good job!

    If you want to design your dialog message with html-elements you have to change the jQuery part from
    $(this).find(‘.modal-body p’).text($message);
    to
    $(this).find(‘.modal-body p’).html($message);

    so you can place images there or just some detailed information of the item to be deleted …

    • Welcome and yes, it should be html if you want to use any html instead of just text.

    • Yes, it should be html if you need to use any HTML instead of plain text.

  • Andrea Biagini

    Thanks for the article.
    I’ve implemented it with success using bootstrap 3, but it seems that with bootstrap 3.1.1 the form is submitted when you click on the submit button instead to wait for the modal to appear.

    • Welcome! I didn’t try 3.1.1 but you may add e.preventDefault() in your handler to stop submission.

      • Andrea Biagini

        Sure, i’ve already done it πŸ™‚

      • Sean

        based on the 3.1.1 documentation e.preventDefault() actually stops the modal from being shown

  • may be you are interested to this:

    Bootstrap Confirm Button
    https://github.com/stefanocudini/bootstrap-confirm-button

  • Eric

    I also had to change button type to “button” instead of “submit” to prevent the modal from disappearing right away. Now the modal will appear, but clicking the “Delete” button on the modal does nothing. Any ideas?

    • You may check the browser’s console for any errors to find out the problem.

  • Dimitar Topalov

    The code does not work for me also – no JavaScript errors, but the dialog shows and hides immediately without waiting and the DELETE is executed.

    • @dimitartopalov:disqus It works for me and tested before posting this article, not sure about your problem, Sorry! Try changing button type to button instead of submit. BTW, I used, BS - 3.0.

      • Dimitar Topalov

        Thank you very much for writing this article and for this suggestion. Changing the button type to button fixed the issue on BS 3.1.1

        Are you planning to write more articles about Bootstrap? Your application’s screenshot looks very nice and I would love to read more about the way you developed it.

        • Glad to know that you have solved the issue. Well, regarding more articles, yes, I have a plan to write new articles but nowadays I’m quite busy with so many things so need a gap and hope I can get a chance very soon. All the best πŸ™‚

  • Jan Sarmiento

    hi! this is unbelievably convenient thanks! but i can’t seem to make the data-title and data-message appear on the modal dialog.

    • Maybe you have any errors in your console, make sure you did everything as described, all the best πŸ™‚

  • Sanoj Bogoda

    Thanks! I just joined this site. Your posts look interesting. I’ve been doing the same thing with Jquery by declaring a common function to show a confirm alert but In this way I can use a nice modal. πŸ™‚

  • Your solution worked if I use a hand coded form but I want to use this on a dynamically generated form and when I click submit, the pop up happens but then it proceeds to the form submission. I wanted to use this in case someone tries to upload and empty file field. Is there some way in your code to use the form ID instead? I think that may fix the issue.

    • How that form would be generated ? Not sure if I understand your question.

      • I’m not sure if you’re familiar with ExpressionEngine, but there is the ability to create a form that allows members to add content from the front end. The form is generated through a pair of opening and closing tags. The form has an ID that can’t be seen until you look at the parsed code on the front end. So I have the modal popping up when someone submits the form but its not actually stopping the form from submitting and hitting cancel doesn’t stop form submission either. Unfortunately I’m not much of a programmer so I don’t know how to change your javascript to stop the form from submitting. I’ve used something similar before which looked at the form ID and I don’t see that in your code.

        • Hello Daniel, I’ve replied you using dcboswel@gmail.com if that’s ok then you’ll get the idea. All the best. I’ve implemented that for one of my projects and gave you the required code. All the best πŸ™‚

          • The solution you sent worked! Thanks so much.

          • Really glad to know that. You are welcome πŸ™‚

          • Guest

            Hi Heera,

            I am having the same problem too. Could you please help me out. When I click the delete button, the modal confirmation box appears but the form submits anyway and the record is deleted without confirming the delete action. Thank you

          • Make sure your browser console does not produce any errors and also make sure you’ve used event.preventDefault(); in the click handler.

  • Ermand Duro

    Thanks. I just used it now and it works perfectly with Laravel 4 πŸ™‚

  • Guest

    How can i used it in my project where passed the delete record value using anchor tag e.g
    without using form, and which part of javascrpit code i should change?

    Delete

  • Md. Zobayer Alam

    How can i used it in my project where passed the delete record value using anchor tag e.g

    href=”config/deleteImage/5″ data-toggle=”modal” data-target=”#confirmDelete” data-title=”Delete Image” data-message=”Are you sure you want to delete this Image?”>

    without using form, and which part of javascrpit code i should change? i am using coideigniter.

  • I’ll add an update about that very soon @mdzobayeralam:disqus

  • vas

    no console errors..but still redirecting to form action page without waiting for confirmation..

    • Probably you should use a button instead of input. Check the other comments, this issue discussed before.

    • ottz

      You should just be confirming that you wish to delete the record, the confirmation is where the data is actually deleted and a message is then generated to tell you that the data was deleted or not.

  • vas

    ya checked..i replaced button type=’submit’ by type=’button’..its working now..thank you

  • ottz

    Awesome… Thanks, ur second option is the go and easy to understand. I made another hidden form field and passed the id in this and the url array I juest left to go to a page which is handled by the route any way, then I picked up the hidden field from the route parameter

  • Nassima

    Hi, very helpful; Thx
    Did you post. tuto about “Γ©dit” button ?
    I have some trouble with form in the modal ( to get vriable to edit)

    • @disqus_gjfQeQRszh:disqus WC, Probably you can figure it out from this tutorial, it would be almost same.

      • Nassima

        yes I’m trying πŸ™‚

        almost, i dont’ know why I have always the first value of my boucle, when I click to edit button.

        even though my modal is inside the boucle

        • @disqus_gjfQeQRszh:disqus, I didn’t see your code so can’t tell anything πŸ™‚

          • Nassima

            I have “Form” in Modal with variable,

            while ($row_me=mysql_fetch_array($resultat_me))

            { ?>

            ///Button

            Edit: "

            ///Modal

            ×
            Modification confirmation

            Nom du Taureau<input type="text" class="form-control" name="taureauNom" value="" required>
            Vous voulez modifier cette donnΓ©e ?

            Annuler
            Modifier

            }?>

          • @disqus_gjfQeQRszh:disqus , You are generating the modal within a loop and using same id id="confirmUpdate" and an id must be unique, two elements can have same id so it’s the problem, make them unique and probably you may use the id from row, like: id="confirmUpdate"+$row_me['id'] but not sure yet because it’s hard to read and get cleear idea from this code but you got the idea.

          • Nassima
          • Nassima

            Okkey ;
            I get you; I will try and see.. thanks πŸ™‚

  • John

    I liked your Actions dropdown in your updated example. I tried it on my page, but the dropdown is appearing behind the bottom of the panel body object. I’ve tried styling a z-index to make it appear in front, but to no avail. Any ideas?

    Thanks,
    John

    • oletis

      You could try modifying your css. for example:

      .modal {
      top:20%;
      }

    • oletis

      Ignore my other suggestion. C&P’d wrong code πŸ™

      .modal {
      transform: translate(0, 17%) !important;
      -ms-transform: translate(0, 17%) !important; /* IE 9 */
      -webkit-transform: translate(0, 17%) !important; /* Safari and Chrome */
      }

  • freddy

    upz after read for some minute it’s not codeigniter, huh !

    • @disqus_38kkGLZYcu:disqus, It’s Laravel but could be implement in CI.

  • D KALYAN KUMAR

    Hi Heera,

    I am new to Laravel (4.2), I am developing a online booking site. I have 2 drop downs, One for Cities and another for Area. If I selected a citi from city table I want to show that citi related areas in area drop down. I have one more doubt how to use PHP and Jquery varable in larave(4.2).

  • D KALYAN KUMAR

    Hi Heera,

    I am new to Laravel (4.2), I am developing a online
    booking site. I have 2 drop downs, One for Cities and another for Area.
    If I selected a citi from city table I want to show that citi related
    areas in area drop down. I have one more doubt how to use PHP and Jquery
    varable in larave(4.2).

    • Hi @dkalyankumar:disqus, This is really quite a broad question, how can i answer this, probably you can search on Stackoverflow or post a question there and send me a link but I believe that, you’ll find answers for this, all the best πŸ™‚

      • D KALYAN KUMAR

        Thank you very much for your valuable suggestions, Heera!

      • D KALYAN KUMAR

        Hi Heera, Finally I completed that Functionality

        Here Is My Code :

        Create.blade.php

        ——————————– Create.blade.php ——————————-

        {{Form::open(array(‘url’=>” , ‘files’=>true))}}

        City Name :

        Select City
        @foreach($cityName as $city)
        id}}” city_code=”{{$city->code}}” city_id=”{{$city->id}}”>{{$city->cityname}}
        @endforeach

        Area Name :

        {{Form::close()}}

        $(‘#city_name’).change(function(e){
        var city_id= $(this).val();
        console.log(e);
        // ajax
        $.get(‘/ajax-area_id?city_id=’+city_id,function(data)
        {
        $(‘#area_name’).empty();
        $.each(data,function(index,areaOjb)
        {
        $(‘#area_name’).append(”+areaOjb.areaname+”)
        $(‘#area_name’).removeAttr(‘disabled’);
        });
        })
        });

        ========================================================

        ————————————– route.php————————————-

        Route::get(‘/ajax-area_id’,function()

        {

        $city_id=Input::get(‘city_id’);

        $areas=AreaNameModel::where(‘city_id’,’=’,$city_id)->get();

        return Response::json($areas);

        });

  • D KALYAN KUMAR

    Hi Heera,

    How to send a array from blade.php to controller.php, And how to convert string to array in laravel 4.2 .

    I want to store dynamic drop downs data in Db, Which is added on click event.

    One more Doubt How I can i send the screen show in post to get some idea on my query.

    • This is not clear but you may use AJAX to send data from client side to server side using JavaScript. Selected Drop down’s value is transferred using any HTML form on submit, no need to do extra work.

  • Hbib Milanista

    Hi Heera,
    Did you use an array to list users?
    because i did a similar work but when i click delete in the modal nothing happens.
    It works without array

  • Very helpful. Thank you

  • D KALYAN KUMAR

    Hi Heera,

    How to save date in db , And i want to change the date format in dd/mm/yyyy. How can i do it.

    Thanks

    • I’m sorry, this is about Bootstrap Modal, what you are trying to say ?

      • D KALYAN KUMAR

        Hi,
        I want to save date and time in DB, Using laravel. And also I want to change the date format to dd/mm/yyyy . For that I taken date field as date type in table creation.

  • Great stuff! Thanks for posting πŸ˜‰

  • Finsok Yagman

    its not working for me…..i am using Bootstrap V3.3.4…..as soon as i click the delete button modal pops out and before i click confirm delete it automatically deletes my post….can any wone help me with this issue

    • Check your browser’s console for errors.

      • Finsok Yagman

        there is no error in my browsers console…..well the modal pop out but i can click confirm delete form the modal

        • Have you used e.preventDefault() in the click handler ?

          • Finsok Yagman

            nope i didnt used e.preventDefault()

      • Finsok Yagman

        Here is what i did same like yours
        Delete Button:
        {!! Form::open(array(‘method’=>’DELETE’, ‘route’ => array(‘packagetypes.destroy’, $packagetype->id))) !!}
        {!! Form::button(‘ Delete’, array(
        ‘class’ => ‘btn btn-danger btn-xs’,
        ‘data-toggle’ => ‘modal’,
        ‘data-target’ => ‘#confirmDelete’,
        ‘data-title’ => ‘Delete Package Type’,
        ‘data-message’ => ‘Are you sure you want to delete this Package Type?’
        ))
        !!}
        {!! Form::close() !!}
        @include(‘_partials.confirm_delete’)

        Confirm delete partial:

        ×
        Delete Parmanently

        Are you sure about this ?

        Cancel
        Delete

        @section(‘script’)

        $(‘#confirmDelete’).on(‘show.bs.modal’, function (e) {
        $message = $(e.relatedTarget).attr(‘data-message’);
        $(this).find(‘.modal-body p’).text($message);
        $title = $(e.relatedTarget).attr(‘data-title’);
        $(this).find(‘.modal-title’).text($title);
        });

        $(‘#confirmDelete’).find(‘.modal-footer #confirm’).on(‘click’, function(){
        $(this).data(‘form’).submit();
        });

        @endsection

        i am not able to fetch modal-body and modal-title also…please do help me

        • Rahul Tathod

          can i set same for view and edit in dialog

    • Eduardo

      Same problem here. When I click on delete button, the modal appears (without the data-title and data-message) but, in about 2 seconds it automatically desappears and deletes my note.

      • Check the console for errors, also read other comments and make sure you are using latest version of bootstrap and don’t forget to e.preventDefault(); to prevent form submit.

        • Eduardo

          Sorry Sheikh, I’m really new into web development. I found no errors on console in the Element Inspector, I added the preventDefault but I dont know if I’m doing it right. I did this code inside the script tag above the javascript code:

          $(‘#confirmDelete’).on(‘click’, function(e) {
          e.preventDefault();
          });

          Still didn’t work.

  • Just for one button:
    {!! Form::open(array(‘method’=>’DELETE’, ‘route’ => array(‘admin.users.destroy’, $user->id))) !!}
    id}}” data-title=”Eliminar Usuario” data-message=”Esta seguro que desea eliminar este usuario?” >
    Eliminar

    {!! Form::close() !!}

  • Karim Amakrane

    I havΓ© Γ  same problem dont work

  • yarfik ardiansyah

    I’m using twitter-bootsrap 3.5.5. e.relatedTarget return ‘undefined’..

  • khudadad

    Hi, I’m getting this error:
    ErrorException in UrlGenerator.php line 278:Route [admin.users] not defined. (View: F:Projectskpucollegeresourcesviewsadminusers.blade.php)
    I’m using Laravel 5.1

    • Make sure you have declared the route using the name admin.users to list all users.

  • Kevin Bradshaw

    In the javasript you have referenced your variables, message and title, using PHP syntax

    $message = $(e.relatedTarget).attr(‘data-message’);
    $(this).find(‘.modal-body p’).text($message);
    $title = $(e.relatedTarget).attr(‘data-title’);
    $(this).find(‘.modal-title’).text($title);

    shouldnt that read:

    var message = $(e.relatedTarget).attr(‘data-message’);
    $(this).find(‘.modal-body p’).text(message);
    var title = $(e.relatedTarget).attr(‘data-title’);
    $(this).find(‘.modal-title’).text(title);

    • That syntax works in JavaScript as well, $ is a valid character in JavaScript and var is optional but good to use.

  • Syed Asad

    Hi good evening brother i need this form for my academic system project if you have all files in .zip or .rar form so show me link plz ? Thanks in advance.

  • Joel

    I am implemented this in laravel 5 but the modal shows for a few secs but proceeds to delete the record anyway.

    I copied the modal form and script and added it as a partial at the bottom of my page –> @include(‘partials.confirmdelete’)

    This is my form:

    {!! Form::open(array(‘route’ => array(‘announcements.destroy’, $announcement), ‘method’ => ‘delete’)) !!}
    {!! link_to_action(‘AnnouncementsController@edit’,’Edit’,$announcement, [‘class’=>’btn btn-default btn-mini’]) !!}
    Delete
    {!! Form::close() !!}

    What am I doing wrong?

  • David Wisenbaugh

    I tried out your code in my application, when I click my delete button the modal comes up but when i click the delete to confirm it just sits there and does nothing. I have copy and pasted your code into mine and nada no delete. Could you possibly tell me why it is not working as intended ? Any help would be appreciated.

Latest Blog