Default submit button for HTML form
Aug 21st, 2007 by robert
Recently I faced well forgotten old problem of having default submit button (activated by Enter while located inside form's filed) for web form. When the behavior of browser is not really standardized, it is common that first submit button is used. In wizard-style forms when you have buttons Back, Save, Continue it is never applicable.
One common solution is to have one more submit button hidden by use of CSS and located before of any visible submit buttons. It works fine in FireFox but no IE. Internet Explorer 7 understands that button is not visible and does not send it's value.
Alternative approach is to sprinkle some JavaScript that will listen to keyboard events, stop event propagation when Enter is pressed and emulate click on desired button. Now when you have such beautiful libraries as Prototype and jQuery it became very simple and elegant:
-
function assignDefaultSubmitButtons(){
-
$j("form").each(function() { // loop throug all forms on the page
-
var _form = this;
-
var _defaultSubmit = _form.getElementsByClassName("defaultSubmit"); // search default submit button
-
if(_defaultSubmit!=null && _defaultSubmit.length>0){
-
$j("input", _form).keypress(function(e){ // attach onkeypress event listener for each input field
-
var keycode;
-
if (window.event) {//IE
-
keycode = window.event.keyCode;
-
}else if (e) { //FF
-
keycode = e.which;
-
}else {
-
return true;
-
}
-
if(keycode==13){
-
_defaultSubmit[0].click(); // emulates click on defaultSubmit button
-
return false; // stops propagating keypress event
-
}
-
});
-
}
-
});
-
}
Now you need to add CSS class 'defaultSubmit' to any submit button and call assignDefaultSubmitButtons when document is loaded. You can have several forms on one page and each of them can have it's own default submit button.
Since we use both libraries jQuery and Prototype, do not forget to add this row:
-
<script>var $j = jQuery.noConflict();</script>