简体   繁体   中英

java script backspace and delete working in IE,not in FireFox

I use the following function for decimal validation it was work fine in IE and Chrome not in FF.Backspace and delete key working in IE and Chrome.Not in FireFox

    $('.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);
            }
        }

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

this if condition not working in FireFox only.this is used to enter the only one dot symbol

if (event.which == 50 ||(event.which == 8 || event.which == 46) && o.indexOf('.') == -1)  {
                return true;
            }

In general, this type of validation needs to be done with care because text can be altered into an input via means other than the keyboard (pasting, text dragging and the Delete option in the context menu, for example). Limiting keyboard input will still need to be accompanied by proper validation when submitting the form.

Use keyCode for detecting the actual key pressed (usually in keydown or keyup rather than keypress ) and which to detect the character typed (only in the keypress event). In general it's not a good idea to look at the keyCode property of keypress events but for the case of delete and backspace it's fine: not all browsers fire a keypress event for these keys but for those that do, the keyCode property is consistent.

In summary: change (event.which == 8 || event.which == 46) to (event.keyCode == 8 || event.keyCode == 46) and leave the rest the same.

Here's the best reference for JavaScript key events I've seen: http://unixpapa.com/js/key.html

 $('#Name_Var').keypress(function (event) { event = event || window.event; var charCode = event.which || event.keyCode; var charStr = String.fromCharCode(charCode); // FireFox key Del - Supr - Up - Down - Left - Right if (event.key !== undefined && event.charCode === 0) { return; } //Only Num if (!/^([0-9])*$/.test(charStr)) { event.preventDefault(); } //Num and letters if (!/^[a-zA-Z0-9]+$/.test(charStr)) { event.preventDefault(); } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM