jQuery 1.4 Live() Form Submit Support
Today, jQuery 1.4 Alpha 1 was released, much to everyone's excitement. In addition to some very awesome performance tweaking, I think one of the most anticipated additions to the jQuery library is the updated functionality of the live() plugin. If you have not used the live() plugin before, it allows for automatic binding of event handlers to DOM elements that may or may not even exist yet. This is some great functionality; but, one aspect that always felt like it was missing was Form-Submit binding. I am sure people will be happy to hear that with jQuery 1.4, form submission can now be live()-bound!
To demonstrate this, I have created a simple demo that contains a form with a single form input and link. Both the form submission and the link click events are live()-bound. When the link is clicked, the form is cloned (duplicated) and appended to the document body. When the form is submitted, the contained input value is appended to the form. Because jQuery's live() binding will automatically "bind" to all future elements matching a given selector, even as I clone page elements, I never have to re-bind the event handlers.
<!DOCTYPE HTML>
<html>
<head>
<title>jQuery 1.4 Live() Form Submit Support</title>
<style type="text/css">
form {
margin-bottom: 30px ;
}
div {
color: #666666 ;
margin-left: 20px ;
}
a {
color: #CD0000 ;
}
</style>
<script type="text/javascript" src="jquery-1.4a1.js"></script>
<script type="text/javascript">
// When the DOM is ready, init the event bindings.
jQuery(function( $ ){
// Bind the live-click event to the links. This will
// close the FORM elements itself.
$( "a" ).live(
"click",
function( event ){
// Find the parent form element.
var form = $( this ).closest( "form" );
// Clone the form element.
var newForm = form.clone();
// Clear the DIV data (from the previous form).
newForm.find( "div" ).empty();
// Add the new form the body.
newForm.appendTo( document.body );
// Reset and focus the first input element.
// NOTE: There appears to be a bug here where
// jQuery cannot use its own FOCUS method. I
// had to get the raw NODE to do that.
newForm.find( ":text" )
.val( "" )
.get( 0 ).focus()
;
// Prevent the default action.
event.preventDefault();
}
);
// Bind the live-submit event to the forms. This
// will take the input text and append it to the
// div element.
$( "form" ).live(
"submit",
function( event ){
var form = $( this );
// Get the input.
var input = form.find( ":input:first" );
// Get the div.
var div = form.find( "div" );
// Append the input value to the div.
div.append(
"<span>Message: " +
input.val() +
"</span><br />"
);
// Select the input text so it can be easily
// overriden by the user.
input[ 0 ].select();
// Prevent the form submission (default action).
event.preventDefault();
}
);
});
</script>
</head>
<body>
<h1>
jQuery 1.4 Live() Form Submit Support
</h1>
<form>
Message:
<input type="text" size="40" />
<input type="submit" value="Submit" />
( <a href="##">clone form</a> )
<div>
<!-- To be filled dynamically. -->
</div>
</form>
</body>
</html>
Pretty cool stuff! What a way to end the week, right?!?
Read more about the jQuery 1.4 Alpha 1 release.
Want to use code from this post? Check out the license.
Reader Comments
Can I be picky? You refer to the live() plugin, but live() is a built in method of the jQuery library. Typically a plugin refers to something you use _along_ with jQuery, a separate download.
@Raymond,
That's a good point. I am not sure why I had the term "plugin" stuck in my head. I must have been working on something else right before?? ... long week.
One thing I'm curious about is - who is running into performance issues? I mean I've definitely had issues with the _size_ of data in Ajax apps, but I've never had issues with... I guess the grunt work (find DOM, change DOM, etc). It's always worked fast. Have you run into stuff where performance improvements would help? (To be clear, more fast == more good, I'm not complaining, but you get my drift.)
I've never used the live method before. Thanks for the intro. Time to go check it out some more.
You may have been thinking the 'Live plugin' because before it was incorporated into jQuery, it was available as a plugin called Live Query.
@Raymond,
I hear what you're saying - I've never run into performance problems myself.
@Julian,
That could be... you might also be giving me too much credit ;)
great to hear about the new release of jquery & also about the live plugin. Thanks for this article.
I tried 1.3.2 with your example, and it still works as you demoed. Is there something different going on behind the scenes with 1.4?
Regardless, I haven't used the live method yet either so this was a great introduction.
~ Ben
@Ben,
If it worked before, it was undocumented (as far as I know). Perhaps it now has fully cross-browser support?
Hey, regarding the focus problem you had. I ran into the same problem recently. This is what I found out after some digging, as I understand it anyway. The reason being is that if you just call your line as follows
newForm.find( ":text" ).focus()
you are dealing with the focus event and any handlers that may be associated with it (focus event of jQuery??).
But on the other hand,
newForm.find( ":text" ).get(0).focus()
actually gets the browser's DOM element and calls the it's focus() method to set it's focus.
I don't believe it has anything to do with 1.4 as I ran into this running 1.3.2
@Yarx,
I actually just tried this on a white page:
$( "input" ).focus();
... and it worked perfectly (tested on 1.4 and 1.4a1). I am not sure why my demo on this blog post did NOT work.
I have, however, come across this focus() issue a few times; so, there must be more to it that I am understanding.
Have you noticed that this works when clicking the button, but doesn't work when calling $('form:first').submit(); from the console? Any ideas how to stop the event when calling from .submit()?
@Steve,
I am not sure if you can. I think philosophically, you can generally not cancel a programmatically-triggered action. I think the idea of cancelling events is only relevant when the event is triggered by a third party (ie. the User). If the code triggers an event, I am not sure cancelling is meant to functional.
This won't work in IE7. It works in other browsers. How do you make it work in IE7?
Your example wont even work for me in IE7.
Found out its a bug in 1.4.2 for IE.
If you got back to 1.4.1 it works all the browsers I tested.
http://dev.jquery.com/ticket/6359
@PJack,
Ah, good to know. I'm personally on the fence about live-submit handling. Something about form submission just feels odd as a bubbling event.
Question from a new jquery user: I'm using load() to add new checkboxes to a long form. When the form is submitted, the new checkboxes are not present. Does this need the new live() ? If so how/where to add it exactly?
Here's my script:
<script type="text/javascript">
function loadContent(id) {
var theid = id;
Verify_Loaded_LI.check(function() {
$('<div id="subs_'+id+' />').load('display/d_loadGCsubcats.cfm?cat_id='+id+' #subcats', function() {
$(this).hide()
.appendTo('#li_'+id)
});
},theid);
}
var Verify_Loaded_LI = {
check: function(runCallback,theid) {
if ($('#subs_'+theid).length == 0) runCallback();
else $('#subs_'+theid).slideDown(1000);
}
}
</script>
@Reincat,
If the checkboxes are not showing up in the form submit, the issue is one of the following:
1) The checkboxes are not checked - only checked checkboxes will be submitted with the form.
2) The checkboxes are not actually inside the FORM tag. A form submission will only submit input elements contained within the given tag.
I hope that helps narrow it down.
@Ben
Thank you, I found the error, the form tags were sitting between table rows and should have been around the entire table. Bad HTML, nothing to do with jQuery. Firebug helped to see that the checkboxes indeed were not inside the form tags.
I did find this was helpful in debugging:
$('#categoryform').live('submit',function() {
alert($(this).serialize());
return false;
@Reincat,
Good catch. I remember I used to put all my FORM tags between TABLE tags back in the day before CSS made it easy to change form margins (if you put the closing FORM tag outside of the TABLE, it would have that huge margin). Problem is, a lot of that code started to break as the browsers got more standards-compliant.
Glad you got it worked out.
Thanks for posting this, helped out a lot.
wordpress-freelancer.com is very fast wordpress job site or project site,
its opened before few years agao and right now going in very right way and providing quality wordpress
jobs and wordpress projects
wordpress-freelancer.com
Thanks for the intro!!!
:)) butifol yours word