Javascript onchange different in IE and FireFox

2019-03-01 04:25发布

问题:

When this onchange event in IE returns false, IE focus stays on that input box. In Firefox the focus always moves to the next field regardless.

HTML:

input name="seminar_donation" type="text" id="seminar_donation"
onchange="return CheckTotal(this);"

JavaScript:

function CheckTotal(inputbox) {  
    if (isNaN(parseInt(inputbox.value))) {  
         alert("Please enter only digits 0-9");  
         inputbox.focus();  
         return false;  
    }  
    return true;  
}  

In IE I don't even need the inputbox.focus() which unfortunately does not appear to do anything in Firefox to retain the focus on the errant input box. How can I get Firefox to stay on that input box?

回答1:

setTimeout('document.getElementById("seminar_donation").focus()',1);


回答2:

A response that no longer appears to be here suggested 'timing' issues, albeit on a slightly different subject. So I googled 'timeout' and found Mike Rankin's blog from 2005 which allowed me to solve the issue by changing focus() to:

var t= setTimeout('document.getElementById("seminar_donation").focus()',1);

So what happens is Firefox still goes on to the next field, but 1 msec later, this code sets the focus back to the errant field. It is cludgy because if that next field has an oblur event that onblur will get triggered when the timeout forces the focus back. But it is a work-around for apparently a long standing bug in Firefox.



回答3:

Have you tried adding a "return" in the onchange attribute? i.e.

<input name="seminar_donation" type="text" id="seminar_donation" onchange="return CheckTotal(this);">

I'm not entirely sure that this would work, but worth a try?

Edit: to clarify, the reason I'm not sure is that I'd usually approach this differently and bind the event handler in javascript rather than html.