Javascript Error in FireFox Not in IE and Chrome

2019-01-29 04:04发布

问题:

I use the following function for decimal validation.the textbox only allow to enter numbers and .(dot) symbol only.It was working fine in IE and Chrome.My problem is I get event is not defined error.How to solve this?I have the lot of textbox validation.so i Create the decimal validation as common its like,

//Call the Function
                             $('.decimalValidate').live('keypress',function(){
                                  var decimalid=$(this).attr("id");
                                  var decimalval=$('#'+decimalid).val();
                                  var decimalvalidate=ApplyDecimalFilter(decimalval);
                                  if(decimalvalidate == false)
                                  return false;
                             });

//Function for Decimal validation.It allows only one . symbol.everything works fine on IE and Chrome

function ApplyDecimalFilter(id)
    {
        try {
              return NewDecimalFilter(id, event);

        } catch (e) {
            alert(e.message);
        }
    }

function NewDecimalFilter(o, event) {

        if (event.keyCode > 47 && event.keyCode < 58) {
            return true;
        }
        if ((event.keyCode == 8 || event.keyCode == 46) && o.indexOf('.') == -1)  {
            return true;
        }
        return false;
    }

And i use this decimalValidate class in text box like as,

input type="text" id="InputLoanAmount" class="decimalValidate" style="width:100px"

回答1:

In firefox, event isn't global. window.event is undefined. You need to pass the event as a parameter. And by the way, you should use .on instead of .live if you use jQuery >= 1.7.

$('.decimalValidate').live('keypress', function (e) {
    var decimalid = $(this).attr("id");
    var decimalval = $('#' + decimalid).val();
    var decimalvalidate = ApplyDecimalFilter(decimalval, e);
    if (decimalvalidate == false) return false;
});

function ApplyDecimalFilter(id, event) {
    try {
        return NewDecimalFilter(id, event);

    } catch (e) {
        alert(e.message);
    }
}

The live demo.