简体   繁体   中英

Disable an input with javascript. Checking the code

I'm doing a client side in javascript and html. I have a problem. I want to check if password and repeat password are the same. In that case I want to disable an input. I saw some codes around but I don't understand why it doesn't work. Can you help me? Here is my HTML:

<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password">
<input class="btn btn-beats btn-block btn-stacked" value="Sign up" onkeydown="enable()" id = "btnPlaceOrder" type="submit">
<input class="form-control form-stacked" name="password" id = "password" placeholder="Password" type="password" required="true">

And then here is my javascript function:

var password = document.getElementById("password");
var repeat = document.getElementById("repeat");
   function enable(){
      if (password.value() == repeat.value()){
         document.getElementById("btnPlaceOrder").disabled = false;
      } else{
         document.getElementById("btnPlaceOrder").disabled = true;
      }
}

Just to be precise, I did the import of the javascript in my HTML

HTML: Add listeners to the password inputs, so the submit button fill change its state as the user types.

<input id="password" type="password" onkeyup="enable()">
<input id="repeat" type="password" onkeyup="enable()">
<input value="Sign up"  id="btnPlaceOrder" type="submit">

JS

function enable(){
    // the comparison returns true or false so no need for if/else
    document.getElementById("btnPlaceOrder").disabled = password.value !== repeat.value;
}

Fiddle: http://jsfiddle.net/40vvL1em/

Well simply call your function in the onkeyup() event of your repeat input.

<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password" onkeyup="enable()">

And here's the JS function:

var password = document.getElementById("password").value;
var repeat = document.getElementById("repeat").value;
function enable(){
if (password === repeat){
  document.getElementById("btnPlaceOrder").disabled = false;
} 
else{
  document.getElementById("btnPlaceOrder").disabled = true;
}
}

That should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM