Question

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?

Was it helpful?

Solution

You might want to try the technique described here: Javascript / Firefox / onBlur

I haven't tried it myself, but essentially it suggests to replace document.form.discount.focus() with

setTimeout(function() {document.form.discount.focus();}, 1);

I suspect the underlying problem is that when you hit tab (for example), the browser goes through a few steps: call the code assosiated with the current control (onchange, onblur), then set the focus to the new control. So if you change focus in the first step, then the focus will still get reset immediately in the next step. Hence the timer-based workaround.

OTHER TIPS

You better convert the discount to a number when you are using it in number comparisions. Change your script to:

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

        else{
            total_bill -= discount;
        }

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top