Defining default buttons in HTML forms using JavaScript
Being a keyboard junky myself, I recently stumbled over the somewhat annoying fact that it seems to be impossible to explicitly tell a web browser what the default button in an HTML form is, i.e. which button will be activated when the user hits the ENTER key. I suspected some kind of “default” attribute to be set on a button, but nada, there simply is no such thing. The default button of an HTML form is always the “submit” button.
This is pretty useless for AJAX applications, where you typically do not want to submit the form by evaluating the action parameter of the form, but instead want to trigger an asynchronous request that carries the data of the form. The obvious solution is to exploit the action parameter of the surrounding form: Instead of providing a server URL, you simply execute the click-handler of the button you want to be the default button:
<script type="text/javascript">
function sendForm() {
alert ("sending data");
}
</script>
<form id="MyForm" action="javascript:sendForm()">
<input type="text" size="50" name="myParam"/>
<input type="button" name="myButton" value="Send"
onclick="sendForm()"/>
</form>
Whenever the user hits the ENTER key, the button’s click-handler is invoked. Technically, no actual click event is fired of course. But it does the job.
Many thanks!
I had the “Enter problem” with my ajax-search-script, and you solve it perfectly with this script :)
Owe you 1 ;)
Спасибо. То, что нужно ))
Great idea! Just what I wanted.
Greetings from Canada,
Carl L.
for me working only with one textbox
Excellent – Worked like a charm