开发者

How to ignore unwanted characters from textbox (JavaScript or jQuery)

开发者 https://www.devze.com 2023-01-31 05:30 出处:网络
There\'s a TextBox that I wanna 开发者_运维问答allow users to just enter numbers & not any alphabetical characters.

There's a TextBox that I wanna 开发者_运维问答allow users to just enter numbers & not any alphabetical characters. So how could I ignore those chars entered by end user via JavaScript or jQuery? Notice I don't wanna replace user's entered value by empty string; Instead wanna ignore case if there is any way for it.


Try that code:

$("#id").keypress(function (e) {
    //if the letter is not digit then display error and don't type anything
    if ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
        return false;
    }
});

reference http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html


You want to attach a handler to the textbox's keypress event. In here check the event.which property to find out what key is pressed, and if it's not a number (between keycodes 48 and 57) return false, which will cancel the default behaviour of typing in the textbox.

$("input").keypress(function (e) {
    if (e.which < 48 || e.which > 57)
        return false;
});


I would not recommend intercepting keystrokes, allow the user to type whatever he/she wants, and validate on user action (submit/select etc).

Look at this jQuery plugin for instance: http://bassistance.de/jquery-plugins/jquery-plugin-validation/


you said you didn't want to include alphabetical then you said you just want to ignore case? what do you need to do?

You can ignore lower case in JS by using string.toLowerCase()


For numeric-only I use this jQuery extension/plug in

http://www.texotela.co.uk/code/jquery/numeric/


In above options we can prevent the user from keyboard, but what if the user paste something, it will not restrict user to not paste any special character.

For example we are restricting it from keyboard with proper error msg

<script type="text/javascript">
    $(function () {
        $("#package").keypress(function (e) {
            var keyCode = e.keyCode || e.which;

            $("#lblError").html("");

            //Regex for Valid Characters i.e. Alphabets and Numbers.
            var regex = /^[A-Za-z0-9]+$/;

            //Validate TextBox value against the Regex.
            var isValid = regex.test(String.fromCharCode(keyCode));
            if (!isValid) {
                $("#lblError").html("Only Alphabets and Numbers allowed.");
            }
            else
            {
                $("#lblError").html("");
            }

            return isValid;
        });
    });
</script>

Now let's prevent it from pasting special character.

$('#package').bind("paste",function(){  
   var data= $('#package').val() ;
   var removedNotAllowed = data.replace(/[^ws]/gi, '');
   $( '#package' ).val(removedNotAllowed);
   $("#lblError").html("Only Alphabets and Numbers allowed.");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消