HTML5中的JavaScript如何启用按钮



,只要用户输入文本,我就试图在JavaScript中启用一个按钮。此代码怎么了?是因为使用字段集吗?

function setText() {
  var x = document.getElementById("mail").value;
  if (x != "") {
    document.getElementById("btn").disabled = 'false';
  }
}
<form>
  <fieldset id="file1">
    <legend><img src="fb-login.png" height="70" width="70" /> :</legend>
    Email: <input id="mail" type="email" onchange="setText()"><br> password: <input type="password"><br><br>
    <input type="submit" id="btn" value="ok" disabled> <br>
  </fieldset>
</form>

以下是正确的方法,而不是使用on Change,您应该使用on Intput/onkeyup:

 function setText(){
  var x=document.getElementById("mail").value.trim();
  if(x !=""){
  document.getElementById("btn").disabled = false;
      }
  else{
  document.getElementById("btn").disabled = true;
      }
    }
 <form>
  <fieldset id="file1">
    <legend><img src="fb-login.png" height="70" width="70"/> :</legend>
       Email: <input id="mail" type="email" onkeyup="setText()"><br>
      password: <input type="password"><br><br>
     <input type="submit" id="btn" value="ok"  disabled> <br>
   </fieldset>
 </form>

update

@mplungjan给出了一个较短的方法:

function setText() {
  document.getElementById("btn").disabled = document.getElementById("mail").value.trim()=="";
}

首先,使用oninput事件代替onchange绑定键入事件。然后,false是JavaScript中的布尔值关键字,而不是字符串。这是一个工作示例:

function setText() {
  var x = document.getElementById("mail").value.trim();
  document.getElementById("btn").disabled = x == "";
}
<form>
  <fieldset id="file1">
    <legend><img src="fb-login.png" height="70" width="70" /> :</legend>
    Email:
    <input id="mail" type="email" oninput="setText()">
    <br> password:
    <input type="password">
    <br>
    <br>
    <input type="submit" id="btn" value="ok" disabled>
    <br>
  </fieldset>
</form>

最新更新