3

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 !

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The first solution breaks if you hold down '.'. The second solution cheats your cat if he/she happens to press it down.
yup, this one is better :) ,but still a little way to go
@karim79 can you help me in this ? stackoverflow.com/questions/5498851/…
3

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/

1 Comment

Alphanumeric breaks on Control+V event :(
1

Use the excellent http://bassistance.de/jquery-plugins/jquery-plugin-validation/ form validation plugin.

All you need to do to validate is issue the options as a class name:

HTML

<input id="test" type="text" class="required email"/>

Adding required and email as a class will validate it as a required input that must be an email. Validation is done as you type.

jQuery

$('#test').validate()

The great thing about this plug-in is you can access the js file directly from Microsoft CDN so you don't' have to load it from your server. http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.