检查输入是否具有特定值

时间:2013-11-27 17:39:21

标签: javascript jquery

我正在使用Jquery来检查输入是否具有特定值,如果它具有该值,则它将启用提交按钮。问题是我将值设置为4,但如果输入44(或以4开头的任何内容),它仍会启用该按钮。此外,一旦输入4,它就可以更改为任何内容,并且按钮保持启用状态。

我希望它只是在值为4时更改为启用,如果值已更改,则应禁用提交按钮。

Jquery的

$(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">

5 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:0)

它的发生是因为如果值不是4,你就不会禁用按钮。

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

答案 2 :(得分:0)

只需添加禁用它的其他内容:)

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

答案 3 :(得分:0)

您需要重新设置它。

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

答案 4 :(得分:0)

使用:

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

<强> jsFiddle example

相关问题