最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery set variable to true and get if var is true - Stack Overflow

programmeradmin0浏览0评论

I am validating form fields, when all form fields are filled out correctly I want to enable the submit button. my validating is working, but not setting a variable to be true and checking that variable. for example..

if(password != confirm_password) {
$("#password_mismatch").css("display", "inline");
} else {
$("#password_mismatch").css("display", "none");
var password_match_valid = true;
return false;
}

this function checks that everything is validated and enables the button

function validate(){
if ($('#name').val().length   >   0   &&
    password_match_valid == true) {
    $('#signup_btn').prop("disabled", false);
}
else {
    $('#signup_btn').prop("disabled", true);
}
}

the bit that is causing problems is

var password_match_valid = true;

and

password_match_valid == true

I am validating form fields, when all form fields are filled out correctly I want to enable the submit button. my validating is working, but not setting a variable to be true and checking that variable. for example..

if(password != confirm_password) {
$("#password_mismatch").css("display", "inline");
} else {
$("#password_mismatch").css("display", "none");
var password_match_valid = true;
return false;
}

this function checks that everything is validated and enables the button

function validate(){
if ($('#name').val().length   >   0   &&
    password_match_valid == true) {
    $('#signup_btn').prop("disabled", false);
}
else {
    $('#signup_btn').prop("disabled", true);
}
}

the bit that is causing problems is

var password_match_valid = true;

and

password_match_valid == true
Share Improve this question edited Dec 12, 2013 at 12:23 Denys Séguret 383k90 gold badges811 silver badges776 bronze badges asked Dec 11, 2013 at 9:13 JakeKempoJakeKempo 5901 gold badge6 silver badges15 bronze badges 1
  • 2 looks like the variable password_match_valid is in a local scope... – Arun P Johny Commented Dec 11, 2013 at 9:15
Add a ment  | 

3 Answers 3

Reset to default 4

This sets a local variable :

var password_match_valid = true;

This variable isn't visible from outside the function in which it's declared, especially it's not visible from the validate function.

A solution is to make it global, by adding

var password_match_valid;

in the global scope and removing the var keyword you currently have.

But it's not clear why the test isn't done in the validate function directly so there might be a cleaner solution, depending on the rest of the code.

Your variable password_match_valid needs to be global. For that declare it outside any function.

var password_match_valid = true;

This var lives only in your else statement. Into validate() function you don't have visibility on password_match_valid. Try with a global var.

发布评论

评论列表(0)

  1. 暂无评论