如何根据if语句更改按钮的颜色?

时间:2015-04-25 18:45:34

标签: javascript html

我目前正在开发一个需要用户注册的网站。在注册表上,我有4个文本字段和一个“注册”按钮。我有一个用户名字段,电子邮件字段,密码字段和确认密码字段。每当用户输入信息时,都会执行多个测试。例如,有一个用户名可用性检查器,一个电子邮件验证器,一个密码匹配检查器和一个密码强度检查器。为了使用户能够注册,我希望所有这些测试都能通过。如果这些测试中至少有一个失败,例如用户的密码不匹配,我不希望注册按钮是可点击的(我也希望注册按钮在不可点击时显示为灰色。这是我的尝试:

首先,我设置了4个变量。每个变量代表一个经历过的测试。

var test1 = 0;
var test2 = 0;
var test3 = 0;
var test4 = 0;

默认情况下,所有测试都设置为“0”,表示测试失败。所以默认情况下,注册按钮应该是不可点击的并且是灰色的。

然后,我自己编辑了测试。如果测试通过,我会将相应的测试变量设置为'1'。例如,这是我的用户名测试:

if(msg == 'OK') //if the username is available
{ 

    $("#username").removeClass("red");
    $("#username").addClass("green");
    msgbox.html('<img src="available.png" align="absmiddle">');
    test1 = 1; //sets the first test variable as passed
}  
else  //if the username is not available
{  
     $("#username").removeClass("green");
     $("#username").addClass("red");
    msgbox.html(msg);
    test1 = 0; //sets the first test variable as failed
}

有很多代码用于使用户名可用性检查工作,但我不认为其余代码对我的问题是必要的。

然后我在其他3个测试中重复相同的想法。电子邮件验证程序,密码强度检查程序和密码匹配检查程序。如果所有4个测试都通过(如果所有4个文本字段都填写正确),则所有测试变量都设置为“1”。

接下来,我设置了一个函数,用于检查测试变量的值以查看它们是否被传递。

function checkButton(){

if (test1 == 1 && test2 == 1 && test3 == 1 && test4 == 1){ //checks if all 4 tests are passed
$("#register").prop('disabled', false); //if they are, make the register button clickable
} else {
$("#register").prop('disabled', true); //if not, make the register button NOT clickable
$("#register").style.backgroundColor = "#A09B9B"; //as well as change the button background color to gray.
}
}

之后,每次在任何字段中按下某个键时,我都会调用该函数。我通过使用'onkeyup'属性来完成此操作。

<input type="text" name="username" onkeypress="return inputLimiter(event,'username'); checkButton()" id="username" maxlength="20" placeholder="Enter your desired username"/><br>
<input type="text" name="email" id="email" onkeyup="checkButton()" placeholder="Enter your E-Mail address here"/><br>
<input type="password" class="password" id="password" name="password" onkeyup="checkStrength(); checkPasswordMatch(); checkButton()" placeholder="Enter a password with more than 5 characters"/><br>
<input type="password" id="password2" onkeyup="checkPasswordMatch(); checkButton()" name="password2" placeholder="Enter the same password you entered above"/><br>

如果看到我的注册表单有效,请访问此处:register form

1 个答案:

答案 0 :(得分:0)

如果您的问题是“如何禁用提交按钮?”,此代码可以帮助您。

此代码禁用提交按钮:

document.getElementById("register").setAttribute("disabled", "true");

这是为了启用它:

document.getElementById("register").removeAttribute("disabled");

使用setAttribute("disabled", "false")将无法启用提交按钮(此处提供更多信息:.setAttribute("disabled", false); changes editable attribute to false

希望这有帮助