简体   繁体   中英

jQuery do not allow alphabets to be entered in input field

My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault() method on both keydown and keyup methods.

 $(function() { // Regular Expression to Check for Alphabets. var regExp = new RegExp('[a-zA-Z]'); $('#test').on('keydown keyup', function(e) { var value = $(this).val(); // Do not allow alphabets to be entered. if (regExp.test(value)) { e.preventDefault(); return false; } }); // End of 'keydown keyup' method. }); // End of 'document ready' 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test" name="test" /> 

What am I doing wrong? Is there some other way to get this done?

Replace

var value = $(this).val();

by

var value = String.fromCharCode(e.which) || e.key;

After all, you need to check which key has been pressed before allowing a character to be typed into the field.

Also, make sure the backspace and delete buttons and arrow keys aren't blocked!

 $(function() { var regExp = /[az]/i; $('#test').on('keydown keyup', function(e) { var value = String.fromCharCode(e.which) || e.key; // No letters if (regExp.test(value)) { e.preventDefault(); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test" name="test" /> 

If your goal is to only accept numbers, dots and commas use this function instead:

 $(function() { var regExp = /[0-9\\.\\,]/; $('#test').on('keydown keyup', function(e) { var value = String.fromCharCode(e.which) || e.key; console.log(e); // Only numbers, dots and commas if (!regExp.test(value) && e.which != 188 // , && e.which != 190 // . && e.which != 8 // backspace && e.which != 46 // delete && (e.which < 37 // arrow keys || e.which > 40)) { e.preventDefault(); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test" name="test" /> 

You need to store input data somewhere and update it each time user inputs allowed character or reset when disabled

$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]'),
    inputVal = '';

$('#test').on('keydown keyup', function(e) {

    var value = $(this).val();

    // Do not allow alphabets to be entered.
    if (regExp.test(value)) {
        $(this).val(inputVal)
    }
    else{ 
        inputVal = value
    }

}); // End of 'keydown keyup' method.

}); // End of 'document ready'

Create a function that will mask it out

jsfiddle

$.fn.noMask = function(regex) { 
  this.on("keypress", function(e) {
    if (regex.test(String.fromCharCode(e.which))) {
        return false;
    }
  });
}

$("input").noMask ( /[a-zA-Z]/ );

If you are trying for only alphabet with space you can try it:

$("#test").on("keypress keyup blur",function (event) { 

 $(this).val($(this).val().replace(/[^a-zA-Z ]/, ""));

if (!((event.charCode > 64 && 
    event.charCode < 91) || event.charCode ==32 || (event.charCode > 96 && 
      event.charCode < 123))) {
      event.preventDefault();
    }
 });

This code will allow only numbers to be accepted for example in a telepone number input field. This is the improvement on the accepted answer.

var regExp = /[0-9]/;
      $("#test").on('keydown keyup blur focus', function(e) {

        var value =e.key;
        /*var ascii=value.charCodeAt(0);
        $('textarea').append(ascii);
        $('textarea').append(value);
        console.log(e);*/
        // Only numbers
        if (!regExp.test(value)
          && e.which != 8   // backspace
          && e.which != 46  // delete
          && (e.which < 37  // arrow keys
            || e.which > 40)) {
              e.preventDefault();
              return false;
        }
      });

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