-1

I'm trying to enable a button in JavaScript as long as the user enter a text . What is wrong with this code?is it because of the using fieldset?

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
dan
  • 91
  • 2
  • 10

2 Answers2

1

Below is the correct approach rather than using onchange you should use oninput / 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

A shorter approach is given by @mplungjan below:

function setText() {
  document.getElementById("btn").disabled = document.getElementById("mail").value.trim()=="";
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
1

First, use oninput event instead of onchange to bind typing events. Then, false is a boolean keyword in JavaScript, not a string. Here is a working example:

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Hulothe
  • 744
  • 1
  • 5
  • 17