Saturday, October 13, 2012

Bringing up a jQuery dialogue before going to a controller

Currently, I'm using CodeIgniter/Bonfire for a website that does your basic CRUD operations. One of the functionalities the user wanted was a confirmation dialogue that the user really wanted to delete an item, which corresponds to an entry in the database. My problem was that, while I knew how to bring up jquery dialogue boxes, I wasn't sure how to redirect the dialogue to the controller that would actually delete that item from the database. My solution was to use the "id" attribute of my delete button.

While iterating through the items returned from the table, print out the name of the item and a delete button beside it. The delete button is really an anchor tag styled to look like a button.

< a class='btn delete' id='".site_url()."modulename/controllername/function_name/{$item->id}'>Delete< /a>

Notice that I didn't use the href attribute. What I would've put in href, I instead put in id. If I hadn't, I wouldn't be able to call the jquery dialogue because the page would instead go to the href link.

Whenever this anchor tag is clicked, this piece of javascript would be run:

$('a.delete').click(function() {
    var dest = $(this).attr('id');
    $('#confirm_delete').css("display", "block").dialog({
          height: 150,
          width: 350,
              modal: true,
              buttons:
              {
            Yes: function(){
              window.location = dest;
            },
            No: function(){
              $(this).dialog('close');
      }}}).dialog('open');});


It's basic jquery, but the key is the assignment of the anchor tag's id attribute. The above code says: when an anchor tag with class 'delete' is clicked, grab that anchor tag's ID attribute and store it in variable "dest". Then look for an html element with the id "confirm_delete" and display it in a dialogue with the following height, width, and buttons: Yes and No.

Just so you know, the div with id = confirm_delete is somewhere on the page with this code:

< div id="confirm_delete" style="display: none;" 
title="Remove item">
Are you sure you want to remove this item?
</ div>

If the user clicks on the "Yes" button, then the user will be redirected to the controller that will actually delete the item. If he chooses "No", then the dialogue just closes. 

No comments:

Post a Comment