Code Like Zell

How to use javascript to hijack the enter key

Within a form, an auxiliary submit button associated with a single text field is often useful. Here’s how to make the ‘enter’ key submit the auxiliary button, as opposed to the entire form.

<form method="post" onsubmit="alert('submitting form')">
  <input type="text" onkeypress="return js_on_enter(event, function(){document.getElementById('aux').click()})">
  <input id="aux" type="button" value="aux submit" onclick="alert('aux');"><br>
  <input type="text"><br>
  <input type="submit" value="form submit">
</form>

Now for the javascript:

<script type="text/javascript">
	function js_on_enter(e, func)  // Takes event instance and js function as params
	{
		if (!e) e = window.event;  // IE appends event instance to window object
		if (e.keyCode == '13')
		{
			func();
			return false;
		}
		return true;
	}
</script>

Thanks for reading, now find something to do at GoLark.com


No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment

How to use ruby variables inside regular expressions How to install memcached