Community Pick: Many members of our community have endorsed this article.

jQuery 1.4 live() and submit event

Julian MatzStaff Engineer
CERTIFIED EXPERT
Published:
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
9,447 Views
Julian MatzStaff Engineer
CERTIFIED EXPERT

Comments (3)

b0lsc0ttIT Manager
CERTIFIED EXPERT

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

bol
Julian MatzStaff Engineer
CERTIFIED EXPERT
Top Expert 2005

Author

Commented:
No problem! And thanks for your feedback b0lsc0tt.

Commented:
Thats very nice document.

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.