获取JavaScript oninput功能来改变背景颜色?

时间:2015-09-28 09:07:22

标签: javascript html css

我有一些代码适用于用户填写其详细信息的密码表单,然后其中2个框只有在输入的数字/年龄大于指定的数字/年龄时才能工作或变得可打字。我现在想更进一步,让用户明白这些盒子只能通过用不同的颜色着色来特定时间进行编辑。由于某种原因,虽然JS中的新代码不起作用。 代码如下:

<div class="container">
  <div class="jumbotron" id="firstform">
    <h1>Sign up page</h1> 
    <form id="myform">

        <label>Username </label> <input type="text" name="uname" id="uname" data-placement="bottom" title="" data-original-title="Username must be unique" class="mytooltip"><br>

        <div class="pwordCheck">
            <label>Password </label> <input type="password" id="pword" data-placement="bottom" title="" onkeyup="passwordValidation(); return false;" data-original-title="Password must be more than 6 characters long" class="mytooltip"><br>
            <label>Confirm Password </label>  <input type="password" id="confpword"  onkeyup="passwordValidation(); return false;" data-placement="bottom" title="" data-original-title="Passwords must match" class="mytooltip">
            <span id="themessage" class="themessage"></span><br> 
        </div>

        <label>Email </label> <input type="email" id="e-mail"><br>

        <label>Age </label> <input type="number" id="age" oninput="ifOfAge(); return false;"><br>

        <label>Can you drive? </label> <input type="text" id="drive" disabled><br>

        <label>What is your occupation? </label> <input type="text" id="occupation" disabled><br>

      <input type="submit" value="Submit" onclick="usernameAlreadyExists(); return false;">
    </form>  

  </div>



</div>  

的CSS:

input#drive{
    background-color: #999;
}

input#occupation{
    background-color: #999;
}

JS:

function ifOfAge() {

  var age = document.getElementById("age");
  var drive = document.getElementById("drive");
  var occupation = document.getElementById("occupation");
  var white = "#fff";

  if (age.value >= 21) {
    drive.disabled = false;
    occupation.disabled = false;
  } else if (age.value >= 16) {
    drive.disabled = false;
    occupation.style.backgroundColor = white;
  } else {
    drive.disabled = true;
    occupation.disabled = true;
    drive.style.backgroundColor = white;
    occupation.style.backgroundColor = white;
  }


}

2 个答案:

答案 0 :(得分:0)

颜色必须用引号括起来。如下。无论你在哪里使用白色环绕它都带引号

 drive.style.backgroundColor = "white";

答案 1 :(得分:0)

您可以为此类禁用输入更改颜色。

修改

function ifOfAge() {

  var age = document.getElementById("age");
  var drive = document.getElementById("drive");
  var occupation = document.getElementById("occupation");
  var white = "#fff";

  if (age.value >= 21) {
    drive.disabled = false;
    occupation.disabled = false;
  } else if (age.value >= 16) {
    drive.disabled = false;
    occupation.style.backgroundColor = white;
  } else {
    drive.disabled = true;
    occupation.disabled = true;
    drive.style.backgroundColor = "#999";
    occupation.style.backgroundColor = "#999";
  }
}

如果您使用jQuery和插件jQuery验证,可以使它更好,或者使用此one更好。