简体   繁体   中英

In jQuery my function is not work

I trying to make two conditional statement with jQuery like this.

$('#user_name, #user_email, #user_password').keyup(function () {
    if ($('#output-name').is('.field-output-comple') &&
            $('#output-email').is('.field-output-comple') &&
            $('#output-password').is('.field-output-comple') &&
            $('#confirm-terms-of-use').is(':checked')
    ) {
        $('#register-button').removeAttr('disabled');
    } else {
        $('#register-button').attr('disabled', 'disabled');
    }
});

$('#confirm-terms-of-use').change(function() {
    if ($('#output-name').is('.field-output-comple') &&
            $('#output-email').is('.field-output-comple') &&
            $('#output-password').is('.field-output-comple') &&
            $('#confirm-terms-of-use').is(':checked')
    ) {
        $('#register-button').removeAttr('disabled');
    } else {
        $('#register-button').attr('disabled', 'disabled');
    }
});

But you know this code is duplicated.

if ($('#output-name').is('.field-output-comple') &&
    $('#output-email').is('.field-output-comple') &&
    $('#output-password').is('.field-output-comple') &&
    $('#confirm-terms-of-use').is(':checked')
) { 
    $('#register-button').removeAttr('disabled');
} else {
    $('#register-button').attr('disabled', 'disabled');
}

So I make this code with function like this.

$('#user_name, #user_email, #user_password').keyup(isValidPassword())
$('#confirm-terms-of-use').change(isValidPassword())

function isValidPassword() {
    if ($('#output-name').is('.field-output-comple') &&
            $('#output-email').is('.field-output-comple') &&
            $('#output-password').is('.field-output-comple') &&
            $('#confirm-terms-of-use').is(':checked')
    ) {
        $('#register-button').removeAttr('disabled');
    } else {
        $('#register-button').attr('disabled', 'disabled');
    }
}

But it does not worked well. No error but isValidPassword dose not output anything maybe. Where did I make mistake? Thank you for reading.

You need to pass the function reference to the event handlers, you are calling the function isValidPassword and is passing the value returned by it undefined as the event handler.

$('#user_name, #user_email, #user_password').keyup(isValidPassword)
$('#confirm-terms-of-use').change(isValidPassword)

This isn't doing what you think:

.keyup(isValidPassword())

This doesn't pass the isValidPassword function itself to keyup , it executes the function and passes the result of that function. And that function doesn't return anything, so its result is undefined .

Don't execute the function, just pass the function itself as a variable:

.keyup(isValidPassword)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM