How to change disabled tag using JQuery multiple times

2654 views javascript
10

I am trying to use JQuery to validate a password and confirm_password pair of fields. The problem I facing is that if I include the following function:

 <script>
        $('#password, #confirm_password').on('keyup', function () {
            if ($('#password').val() == $('#confirm_password').val()) {
                $('#message').html('Matching').css('color', 'green');
                $("#submit").prop('disabled',false);
            } else 
                $('#message').html('Not Matching').css('color', 'red');


        });
    </script>

Then when the passwords match the submit button becomes enabled. However, if the password are then changed so they don't match the submit button remains enabled.

If I include the following line in the else statement:

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

Then the submit button is always disabled no matter whether the passwords match or not.

Can someone please explain what I am missing and how to correct this problem?

answered question

1 Answer

1

Make your else a block

$('#password, #confirm_password').on('keyup', function () {
    if ($('#password').val() == $('#confirm_password').val()) {
        $('#message').html('Matching').css('color', 'green');
        $("#submit").prop('disabled',false);
    } else {
        $('#message').html('Not Matching').css('color', 'red');
        $("#submit").prop('disabled',true);
    }
});

Without the curly braces only the message is executed by the else and the disabled is always executed.

I would recommend always using curly braces even if you only want to execute a single statement. Makes reading and maintaining code clearer.

posted this

Have an answer?

JD

Please login first before posting an answer.