Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate user input on keypress on textbox jQuery

How to code in jQuery so a user can not press dot "." key in a text box ?

i can code it in javascript like that, on each keypress the browser checks if a key is pressed, if it is dot then substring(0,len-1), but it flickers ! i want to completely block pressing the key !

like image 347
Sourav Avatar asked Mar 05 '26 22:03

Sourav


2 Answers

This should work. It has not been cross-browser tested:

$("#theTextBox").keyup(function() {
    if($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
});

You can try it here.

EDIT: I think this is better:

function doItPlease() {
    if ($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
}

$("#theTextBox").bind("keydown keyup", doItPlease);

Try the less sucky solution here.

EDIT (again): I favour the above solution, because I quite like the feedback aspect. That said, I think this is what you're after:

$("#theTextBox").keyup(function(e) {
    if (e.which != 190) {
        return true;
    }
    e.preventDefault();
});

Try it here.

like image 159
karim79 Avatar answered Mar 08 '26 12:03

karim79


Have a look at this plugin to prevent specific characters being entered: http://www.itgroup.com.ph/alphanumeric/

Also have a look at the validation plugin for general validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

like image 31
Mark Redman Avatar answered Mar 08 '26 10:03

Mark Redman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!