JavaScript onchange, onblur, and focus weirdness in Firefox

Posted by typoknig on Stack Overflow See other posts from Stack Overflow or by typoknig
Published on 2011-01-09T17:46:55Z Indexed on 2011/01/09 17:53 UTC
Read the original article Hit count: 278

Filed under:
|
|
|
|

On my form I have a discount field that accepts a dollar amount to be taken off of the total bill (HTML generated in PHP):

echo "<input id=\"discount\" class=\"text\" type=\"text\" name=\"discount\" onkeypress=\"return currency(this, event)\" onchange=\"currency_format(this)\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this); calculate_bill()\"/><br/><br/>\n";

The JavaScript function calculate_bill calculates the bill and takes off the discount amount as long as the discount amount is less than the total bill:

    if(discount != ''){

        if(discount - 0.01 > total_bill){
            window.alert('Discount Cannot Be Greater Than Total Bill');
            document.form.discount.focus();
        }

        else{
            total_bill -= discount;
        }

    }

The problem is that even that when the discount is more than the total bill focus is not being returned to the discount field. I have tried calling the calculate_bill function with onchange but neither IE or Firefox will return focus to the discount field when I do it like that. When I call calculate_bill with onblur it works in IE, but still does not work in Firefox. I have attempted to use a confirmation box instead of an alert box as well, but that didn't work either (plus I don't want two buttons, I only an "OK" button).

How can I ensure focus is returned to the discount field after a user has left that field by clicking on another field or tabbing IF the discount amount is larger than the total bill?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about firefox