<

jQuery 1.4 live() and submit event

Published on
14,834 Points
8,534 Views
3 Endorsements
Last Modified:
Approved
Community Pick
by Julian Matz

As of jQuery 1.4 the .live() method supports custom events as well as some standard JavaScript events that it previously didn't support. Among these is the submit event.

Unlike other event listeners, the .live() method also works on DOM nodes that are dynamically loaded, making it very useful if you're working with AJAX for example. With .live('submit') we can now do event handling with HTML forms... Or at least I thought we could. Unfortunately, .live('submit') does not currently work with Internet Explorer.

I recently faced a problem where I needed to come up with an alternative to the .live('submit') method that worked with both Firefox and Internet Explorer. I was able to develop a work-around by using the .live('click') method, and I decided to share with you how I made this solution work.

Below is the code I used to solve the problem, along with a sample HTML form.

The HTML form was retrieved using an AJAX request, and this is why I needed to use the jQuery .live() method. The reason I couldn't have used a different method, like .submit(), for binding my event handler to the submit event is that this method only listens to events for already existing DOM elements, and since my AJAX request loaded the form elements as new DOM nodes, this wouldn't have worked. The .live() method, on the other hand, attaches "a handler to the event for all elements which match the current selector, now or in the future" (with future being the keyword).

I also wanted the form to be sent using AJAX, and for the results to display in the same container as the form was initially loaded in.

The form posts to a page named "ajax.php" as specified in the line of code beginning with "jQuery.post()," and the results are displayed in a <div> element with a specified id attribute value, in this case "plugin_form_container." You'll see that the "plugin_form_container" id is appended to the action attribute of the form following a hash character.

<form class="ajax" action="./?p=page#plugin_form_container" method="post">

Open in new window


Using JavaScript's replace() method to strip everything before the hash, allows access to the id of the <div> element in which the results will be displayed. Here's the snippet of JavaScript needed:

var result = jQuery(this).attr('action').replace(/^.*#/,'#');

Open in new window


Since using .live('submit') will not work with Internet Explorer, I was able to use the .live('click') method to capture the form submission and then used the jQuery.post(), which is a shorthand AJAX function, to post the form data.

The script used for this is:

jQuery("form[class='ajax'] input[type='submit']").live('click',function(e) {

Open in new window

and
jQuery.post("ajax.php", f.serialize(), function(data) {

Open in new window


That script selects form elements that have a class attribute with the value "ajax" and listens for a click event on that form's submit button. If you instead used a <button> element, you could simply change the script to:

jQuery("form[class='ajax'] button[type='submit']").live('click',function(e) {

Open in new window


To conclude, this solution is basically a flexible event handler that will capture HTML form submissions and post the data using an AJAX request. What makes it so flexible is that it will work with all DOM elements, even if they are loaded dynamically using AJAX or other JavaScript methods, and the form results can be loaded into any existing container on the page by simply appending the action attribute with a hash, followed by the id of the container you'd like to use. Also, no inline JavaScript is needed on the page itself, and can be included using an external .js file.

Hopefully someone will find this useful. If you have any comments about this article or my solution, don't hesitate to give me a shout.
<script type="text/javascript">
jQuery(document).ready(function() {
      jQuery("form[class='ajax'] input[type='submit']").live('click',function(e) {
            var f = jQuery(this).parents('form:first');
            f.submit(function() {
                  var result = jQuery(this).attr('action').replace(/^.*#/,'#');
                  jQuery.post("ajax.php", f.serialize(), function(data) {
                        jQuery(result).html(data);
                  });
		  return false;
            });
      });
});
</script>

<div id="plugin_form_container">
	<form class="ajax" action="./?p=page#plugin_form_container" method="post">
		<table width="100%">
			<tr>
				<td class="r">Test</td>
				<td><input type="text" name="test" value="" size="45"></td>
			</tr>
			<tr>
				<td></td>
				<td>
					<input type="hidden" name="p" value="plugin" />
					<input type="hidden" name="m" value="module" />
					<input type="hidden" name="a" value="add_record" />
					<input type="submit" value="Submit" />
				</td>
		</table>
	</form>
</div>

Open in new window

3
Comment
Author:Julian Matz
3 Comments
 
LVL 54

Expert Comment

by:b0lsc0tt
Interesting article!  Thanks for the time to write it and sharing it with us.

bol
0
 
LVL 21

Author Comment

by:Julian Matz
No problem! And thanks for your feedback b0lsc0tt.
0
 

Expert Comment

by:sapamja
Thats very nice document.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Join & Write a Comment

The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month