簡體   English   中英

檢查輸入是否具有特定值

[英]Check if input has specific value

我正在使用 Jquery 檢查輸入是否具有特定值,如果它確實具有該值,它將啟用提交按鈕。 問題是我將值設置為 4,但如果輸入 44(或以 4 開頭的任何內容),它仍會啟用按鈕。 此外,一旦輸入 4,它可以更改為任何內容,並且按鈕保持啟用狀態。

我希望它做的是僅在值為 4 時更改為啟用,如果值更改,則應禁用提交按鈕。

查詢

$(document).ready(function() {
    $('#check').keyup(function() {
        if($(this).val() === '4') {
            $('.submit').removeAttr('disabled');
        }
    });
});

HTML

<input id="check" type="text" name="check" />

<input type="submit" name="submit" class="submit" disabled="disabled">

試試這個:

$('#check').change(function() {
    if($(this).val() === '4') {
        $('.submit').removeAttr('disabled');
    }
    else $('.submit').attr('disabled', 'disabled');
});

實際上,當值不是4時,如果您願意,您需要重新禁用提交按鈕。

更好的是,而不是

$('.submit').attr('disabled', 'disabled');

你可以/應該使用

$('.submit').prop('disabled', true);

所以處理程序變成

$('#check').change(function() {
    if($(this).val() === '4') {
        $('.submit').removeAttr('disabled');
    }
    else $('.submit').prop('disabled', true);
});

甚至更簡單

$('#check').change(function() {
    $('.submit').prop('disabled', $(this).val() !== '4');
});

它的發生是因為如果值不是 4,你沒有禁用按鈕。

$('#check').keyup(function() {
    if($(this).val() === '4') {
        $('.submit').removeAttr('disabled');
    }
    else{
        $('.submit').attr('disabled','disabled');
    }
});

只需添加一個禁用它的 else :)

$(document).ready(function() {
    $('#check').keyup(function() {
        if($(this).val() === '4') {
            $('.submit').removeAttr('disabled');
        } else {
            $('.submit').prop('disabled', true);
        }
    });
});

您需要重新禁用它。

$(document).ready(function() {
    $('#check').change(function() {
        if($(this).val() === '4') {
            $('.submit').removeAttr('disabled');
        }else{
            $('.submit').prop('disabled');
        }
});

使用:

$('#check').keyup(function () {
    $('.submit').prop('disabled', $(this).val() !== '4' );
});

jsFiddle 示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM