views:

630

answers:

3

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?

A: 

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.

Graza
Oh yes, I tried it with return, makes no difference.
Jim Thomas
I changed the source to "return CheckTotal(this) for the benefit of other viewers.
Jim Thomas
+1  A: 

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.

Jim Thomas
idem comment like @Dave.Sol
helios
You don't even need the timeout length to be 1, it can be 0 - timer execution is queued until the thread is idle so the currently firing list of events has priority.
Andy E
+1  A: 

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

Dave.Sol
I assume you answer this because Firefox first calls your event handler and NEXT focus the next input, override the focus() in the handler. In that case what it's doing is saying javascript to execute later (1 ms). Javascript is monothreaded so it's the same like "invoke after you have finished all this".
helios
@helios, yes it happens as you described it.
Dave.Sol