Hitting enter does not invoke javascript function in HTML form
I have a simple form with one input field. It works fine when I use the submit but hitting enter in the text field reloads the page with开发者_StackOverflow社区 the form variable in the URL.
I looked through the many solutions available online (except for JQuery since it seems like overkill for something this simple) and haven't been able to get 'enter' to work. Any help would be great
<form name="myform" action="" method="GET" > Enter text: <br>
<input type="text" name="queryinput" onkeyup="if(isEnterPressed(event)){initialize(this.form.queryinput.value);}"><P>
<input type="button" name="Search" value="Search" onClick="initialize(this.form.queryinput.value);">
<input type="submit" value="Reset" onclick="reset();" />
</form>
function isEnterPressed(e){
var keycode=null;
if (e!=null){
if (window.event!=undefined)
if (window.event.keyCode) keycode = window.event.keyCode;
else if (window.event.charCode) keycode = window.event.charCode;
}else{
keycode = e.keyCode;
}
}
return (keycode == 13);}
Edit 1: Version using onsubmit instead of the keycode listeners:
<form name="myform" action="" onsubmit="return initialize(this.form.queryinput.value)" method="GET"> Enter text:<br>
<input type="text" name="queryinput">
<input type="submit" value="submit" >
<input type="button" value="Reset" onclick="clearAllPoints();"/>
</form>
Using onSubmit causes the click button to behave the same as hitting enter but neither version works.
Try using the onSubmit
event for the form
rather than the onClick
event for the input
element. It seems that onClick
is firing only when it's physically clicked by a mouse (which makes sense, I've just never encountered it like this I guess). The onSubmit
event, however, should fire regardless of how the form is submitted.
If you set your field outside of the form, it will not auto-submit the form when you press enter. Then you can have your button copy the text inside the input field to a hidden field inside the actual form and then submit it.
--edit, added code--
Enter text:<br>
<input type="text" id="myinputfield">
<form name="myform" id="myform" action="" method="GET">
<input type="hidden" name="queryinput" id="queryinput">
<input type="button" value="Submittal button" onclick="doSubmitForm();" />
</form>
<script type="text/javascript">
function doSubmitForm(){
itm1 = document.getElementById('myinputfield');
itm2 = document.getElementById('queryinput');
if (!itm1 || !itm2) return false;
//You could put form input verification here
itm2.value = itm1.value;
document.forms["myform"].submit();
}
</script>
精彩评论