Skip to content
Advertisement

Check if input has specific value

I am using Jquery to check if an input has a specific value and if it does have that value it will enable the submit button. The problem is I set the value to 4 but if 44 (or anything that begins with 4) is entered it still enables the button. Also once 4 is entered it can be changed to anything and the button remains enabled.

What I would like it to do is only change to enabled if the value is 4 and if the value is changed then the the submit button should be disabled.

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

Advertisement

Answer

Try this:

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

in fact you need to re-disable the submit button if you wish so when the value is not 4.

Better yet, instead of

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

you could/should use

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

so the handler becomes

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

or even simpler

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