user1893822
user1893822

Reputation: 57

Tab key not working in jQuery

This is my code for validating numeric values only, which works.

But I get an alert message when I press the tab key.

$j('#ctl00_cphMain_txtQuantity').keypress(function (event) {
    if ((event.which != 46 || $j(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which !=8)  ) {
        event.preventDefault();
        alert("Please Enter Valid Quantity");
    }

Upvotes: 1

Views: 794

Answers (5)

Rijo
Rijo

Reputation: 2718

There are issues with regex in FireFox. It may not work with tab key test. I used following code and got worked on all browsers

jQuery(document).on( "keypress", ".element1, .element2", function(e) {
        var regExp = new RegExp("^[a-zA-Z \b]*$");
        var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);

        if (e.keyCode != 9) { // For FireFox
            if (!regExp.test(key)) {
                e.preventDefault();
                return false;
            }
        }

    });

Upvotes: 0

Jai
Jai

Reputation: 74738

Adjust your code at these places:

$j('#ctl00_cphMain_txtQuantity').keypress(function (event) {
if ((event.which != 46 ||  
    $j(this).val().indexOf('.') != -1) && 
    (event.which < 48 || event.which > 57) && 
    (event.which !=8)  ) {
//              ---^----------------------------9 is the tabkey     
        event.preventDefault(); // <------------remove this
        alert("Please Enter Valid Quantity");
}

i have done something in this fiddle which gets alerts when other keypress event happens but not the tab key: http://jsfiddle.net/8YNFw/

you can find the keycodes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

My suggestion would be to use regex instead of keycodes, as there is an arbitrary number of keycodes you'll need to account for. What about CTRL? Or SHIFT?

Try this:

$("#foo").keyup(function() {
    var $input = $(this);
    var regex = /^\d+$/;

    if (!regex.test($input.val())) {
        alert("Please enter numeric values only");
        $input.val($input.val().replace(/\D/, ''));
    }
});

Example fiddle

Upvotes: 1

Stefan
Stefan

Reputation: 14893

Use keydown instead of keypress instead of keydown.

Sample:

        $('#test').keydown(function (event) {
            if (((event.which != 46) ||
                 ($(this).val().indexOf('.') != -1))
                && ((event.which < 48)
                    || (event.which > 57))
                && (event.which != 8)) {
                event.preventDefault();
                alert("Please Enter Valid Quantity");
            }
        });​

Upvotes: 0

If you add an event.keyCode!=9 in the if clause it should work.

Upvotes: 0

Related Questions