2016-09-20 502 views
0

我希望按钮在表单有效时更改颜色,而不必点击任何内容或调用某个函数(如单击提交按钮)。只要表格有效,按钮应该变成蓝色,我无法理解这一点,任何帮助都将不胜感激。当表单有效时更改提交按钮颜色

HTML

<form id="email_login" method="post"> 
    <label for="email" class="form_login" id="email_text">Email</label><br> 
    <input type="text" placeholder="Enter Email" name="email" class="email_login_boxes" id="email_box" > 
    <div class="error" id="error_email"></div> 

    <label for="password" class="form_login" id="password_text">Password</label> 
    <input type="password" placeholder="Enter Password" name="password" class="email_login_boxes" id="password_box" > 
    <div class="error" id="error_password" ></div> 

    <input type="submit" value="LOGIN" id="submit_btn" /> 
</form> 

jQuery的

$("input").on("keydown", function (e) { 
    return e.which !== 32; 
}); 

$("#error_email").hide(); 
$("#error_password").hide(); 

var error_email = false; 
var error_password = false; 

$("#email_box").click(function(){ 
    $("#error_email").hide(); 
}); 

$("#password_box").click(function(){ 
    $("#error_password").hide(); 
}); 

$("#email_box").focusout(function(){ 
    check_email(); 
}); 

$("#password_box").focusout(function(){ 
    check_password(); 
}); 

function check_email() { 
    var pattern = new RegExp(/^[+a-zA-Z0-9._-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i); 

    if(pattern.test($("#email_box").val())) { 
     $("#error_email").hide(); 
    } else { 
     $("#error_email").html("Invalid email address"); 
     $("#error_email").show(); 
     error_email = true; 
    } 

} 

function check_password() { 
    var password_length = $("#password_box").val().length; 
    if (password_length < 5) { 
     $("#error_password").html("Must be greater than 5 characters"); 
     $("#error_password").show(); 
     error_password = true; 
    } else{ 
     $("#error_password").hide(); 
    } 
} 

$("#email_login").submit(function() { 

    error_email = false; 
    error_password = false; 

    check_email(); 
    check_password(); 

    if(error_password == false && error_email == false) { 
     return true; 
    } else { 
     return false; 
    } 

}); 

回答

0

尝试这样的事情。

$("#email_login input").change(function() { 
    // Validating here 

    // Change button if validated here 
}); 

无论何时在#email_login中更改输入时都会调用更改函数,因此每次更改都会进行验证。如果验证成功,则更改按钮(并可能禁用文本框)

2

您说过“只要表单有效,按钮应该变为蓝色”。这意味着表单应该在每个输入事件之后进行验证,或者当用户将鼠标从输入字段中移出时。

试试这个:

$("input, textarea").on("keydown keypress keyup paste mouseout", function() { 

    var formValid = validationFunction(), 
     bgColor = formValid ? "blue" : "red"; 

    $("#submit_btn").css("background", bgColor); 

});