Button onclick works fine but undesired behavior when pressing enter to submit form
I'm not sure if I need a form for this, it's a javascript that takes an input from a textbox, does some calculation on it, and displays the results in a div. I just want the user to be able to submit by clicking submit or by pressing enter.
In short, if the button type is "button", clicking works fine but pressing enter works strangely, and if the button type is "submit", pressing enter works fine, but clicking works strangely. Below is a sample of the code (removed some business logic and other variables that were working fine to make it simpler to display here):
<form action="#" onsubmit="calcserial()">
Serial no: <input type="text" name="serialno" id="serialno" /><br />
<input type="button" value="Submit" onclick="calcserial()" />
</form>
<script type="text/javascript">
function calcserial(){
var x=document.getElementById('serialno').value;
var year=[business logic];
var month=[business logic];
document.getElementById('results').innerHTML="Shipped: " + month + ", " + year;
}
</script>
<div id=results></div>
To give more detail about the strange behavior, when input type is "button" and I press enter, rather than running the calcserial() function, the textbox is cleared and the url is changed to:
[filename].php?serial开发者_如何学运维no=[value]#
With [value] being what ever was in the text box. Then, if I put in the same exact value again and press enter again, it works as intended, but only if the url already shows the value I am submitting. If I enter a different value, the text box is cleared again and the url is changed to show the new value. If I switch the input type to "submit", the problem is resolved for pressing enter, but the same problem then occurs when clicking the button to submit.
Why is this happening? Any ideas how to resolve it? Thanks!
Try changing this:
<form action="#" onsubmit="calcserial()">
To this:
<form action="#" onsubmit="calcserial();return false;">
That should stop the default action that would normally happen on submit of a form, which in your case with action="#"
results in the same page being reloaded.
Given that you don't actually want to submit anything (to the webserver) you don't really need a form for this. An <input type="button">
plus checking for enter onkeyup
of the text input could achieve the same effect.
精彩评论