Onsubmit event can silently kill onchange event, if called simultaneously. I assume race condition in js engine. Tested in chrome, FF3, FF6 and IE9.
To reproduce you need to change contents of input and click on submit button. Do not make any additional clicks between input change and submit button click.
<div id="somediv">
<div>one</div>
<div>two</div>
</div>
<form method="POST" id="someform">
<input type="text" name="input1" id="someinput" value="change me" />
<input type="submit" />
</form>
<script type="text/javascript">
document.getElementById('someinput').onchange = function() {
//some delay - DOM operations, AJAX or alert:
document.getElementById('somediv').getElementsByTagName('div')[1].style.display = 'none';
//or alert('123');
}
document.getElementById('someform').onsubmit = function() {
alert('This event is not called');
}
</script>
Expected behavior: onchange event, than onsubmit.
If we use button instead of submit and call events one after another - everything works as expected.
If there is no operations (no delay) in onchange event - works as expected.
If onchange will change div's color (not display) - sometimes (3/10) works as expected, lol.
js-guru, please, explain, what the hell is going on?
onsubmit works like onclick, which requires onmousedown and onmouseup events consecutively. If your code shows a dialog (eg. alert) or replaces the button after onmouseown event, consequent onmouseup is not fired and thus cancels the event. Swapping the textbox and button with somediv should help.
Note that there has been problems with JS engine not running the submit when a dialog box is open: Javascript onchange event preventing onsubmit event in HTML form?
It turns out that it is only presence of an alert() - or a confirm() - during the input's onchange event that causes the form's onsubmit event to not fire. The JS thread appears to get blocked by the alert(). The workaround is to not include any alert() or confirm() in the input's onchange call.
It's likely that they worked around that bug by disallowing alert() or confirm() commands in the onchange call to allow the form to submit as expected.
来源:https://stackoverflow.com/questions/8013282/onsubmit-event-silently-killed-by-onchange