1

これは、数値のみを検証するための私のコードであり、機能します。

しかし、tabキーを押すと警告メッセージが表示されます。

$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");
    }
4

5 に答える 5

1

キーコードの代わりに使用することをregexお勧めします。考慮する必要があるキーコードの数は任意です。どうCTRLですか?それともSHIFT

これを試して:

$("#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/, ''));
    }
});

フィドルの例

于 2012-12-13T08:52:03.673 に答える
0

これらの場所でコードを調整します。

$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");
}

私はこのフィドルで何かをしましたが、他のキー押下イベントが発生したときにアラートを受け取りますが、タブキーは受け取りません:http://jsfiddle.net/8YNFw/

ここでキーコードを見つけることができます:http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

于 2012-12-13T08:59:59.390 に答える
0

keydown の代わりに keypress の代わりに keydown を使用します。

サンプル:

        $('#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");
            }
        });​
于 2012-12-13T08:53:45.837 に答える
0

if 句に event.keyCode!=9 を追加すると、機能するはずです。

于 2012-12-13T08:49:11.850 に答える