Using jQuery Alerts plugin to submit a form

Using jQuery Alerts plugin to submit a form

jQuery is awesome. The jQuery Alerts plugin is also awesome. One of the most immediate and obvious uses of the pair is presenting a spiffy confirmation box before submitting a form. For example, I recently implemented this setup on a form that ultimately deletes data. I couldn’t find a detailed example for this setup, leading to much trial and error. Here’s what worked for me.

First the form…

Option 1
Option 2Take note that we are dealing with a normal form, nothing fancy about the form action, the inputs, etc. The only thing special going on here is that we’ve substituted an actual <input type="submit" ... /> button for a plain button type and attached an onclick event.

Now the JavaScript…

function confirmDelete() {
  jConfirm('Are you sure you want to delete this stuff?', 'Please Confirm', function(result){
    if (result) {
      $("form[name='action_delete']").submit();
    } else {
      return false;
    }
  });
}
$(document).ready(function(){
  // [ ... ]
});

Assuming you understand the syntax for jQuery Alert, the confirmDelete() function is fairly straightforward. It’s everything around the jConfirm() call that gave me a headache.

Go back to the fact that we’re using a regular button and onclick, instead of a submit button and the onsubmit event. Nested jQuery functions, like jConfirm() and its third argument, have always caused me problems with normal JavaScript events, onsubmit in particular. If not done properly, the submit event is not “held up” by the confirmation dialog, input validation, etc. Such was the case here, so the only submit event occurs in the JavaScript after getting validation from the prompt.

Also note the position of confirmDelete(): outside of the jQuery “document ready” block. If you put it inside, it won’t work.

I explicitly identified the form to submit (line 4 in JavaScript) for sake of code clarity. This layout can easily be modified to dynamically process multiple forms.

Finally, note that this setup requires JavaScript to work, i.e. it does not gracefully degrade. In my opinion, the situations where this is actually a problem are limited. Every major browser on the market fully supports JavaScript, and enables it by default. Unless your target audience is 100% mobile (you should build a separate interface for your mobile app anyway) or in a high security sector, assuming its presence is a very safe bet.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s