Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to allow only defined characters as input using jQuery?

How do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?

As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters. for example: limitCharacters(textid, pattern)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

?You can just check the keyCode on keydown and run preventDefault() if match:

$('input').keydown(function(e) {
    if (e.which == 8) { // 8 is backspace
        e.preventDefault();
    }
});?

http://jsfiddle.net/GVb6L/

If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:

$.fn.restrict = function( chars ) {
    return this.keydown(function(e) {
        var found = false, i = -1;
        while(chars[++i] && !found) {
            found = chars[i] == String.fromCharCode(e.which).toLowerCase() || 
                    chars[i] == e.which;
        }
        found || e.preventDefault();
    });
};

$('input').restrict(['a',8,'b']);?

http://jsfiddle.net/DHCUg/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...