【问题标题】:How do I change the color of a button depending on an if statement?如何根据 if 语句更改按钮的颜色?
【发布时间】:2015-04-25 18:45:33
【问题描述】:

我目前正在开发一个需要用户注册的网站。在注册表单上,我有 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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

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

    此代码禁用提交按钮:

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

    这是为了启用它:

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

    使用setAttribute("disabled", "false") 不会启用提交按钮(更多信息在这里:.setAttribute("disabled", false); changes editable attribute to false

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多