gpt4 book ai didi

javascript - 表单有效时更改提交按钮颜色

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:51 24 4
gpt4 key购买 nike

我希望按钮在表单有效时改变颜色,而无需单击任何内容或调用函数(例如单击提交按钮)。一旦表单有效,按钮就会变成蓝色,我无法理解这个问题,非常感谢任何帮助。

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._-]+@[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;
}

});

最佳答案

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

试试这个:

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

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

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

});

关于javascript - 表单有效时更改提交按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39593178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com