HTML:
<button class="search" name="search">search</button>
Javascript:
$('button.search').live('click', function(event) {
var newForm = jQuery('<form>', {
'action': 'http://www.google.com/search',
'target': '_top'
}).append(jQuery('<input>', {
'name': 'q',
'value': 'stack overflow',
'type': 'hidden'
}));
newForm.submit();
});
Fiddle: http://jsfiddle.net/YqGLH/90/
Expected behavior: when clicking on the search button, page should forward to google search. Works as expected in latest Chrome, Safari and Opera.
Does not work in latest FF and IE9. Clicking the button silently fails, no error messages, no forwarding happens.
What am I missing here?
It's also worth mentioning that you must add the form to the
body
element, not the document. Chrome is forgiving and will work when the form is just added to thedocument
element, but IE and Firefox will need you to add it to thebody
element specifically.I don't have a reference to any particular specification to support the why, but I believe it will work if you append the new form to the page:
Note also that it would be a good idea not to keep using
.live()
in any new code, given that it has been removed from the latest version of jQuery. Instead use:(Ideally specifying a parent element closer to the button rather than
document
.)