JavaScript onchange, onblur, and focus weirdness in Firefox

一个人想着一个人 提交于 2019-12-11 05:15:54

问题


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?


回答1:


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.




回答2:


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;
        }

    }


来源:https://stackoverflow.com/questions/4640687/javascript-onchange-onblur-and-focus-weirdness-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!