简体   繁体   中英

How does onchange and onkeyup work in javascript?

I was trying to validate a password field when I found the javascript code on the net. Can someone please explain when is the "onchange" fired and why does the code not work when I replace onkeyup with onchange (last 2 lines in javascript code)

 function validatePassword(){ if(password.value != confirm_password.value) { confirm_password.setCustomValidity("Passwords Don't Match"); } else { confirm_password.setCustomValidity(''); } } password.onchange = validatePassword; confirm_password.onkeyup = validatePassword;
 <div class="password" id="password-fields" style="display:none"> Password: <input type="password" name="password" class="password" id="password"><br> Confirm Password: <input type="password" name="password" class="password" id="confirm-password"> </div> <div> <input type="submit" name="submit"> </div> </form>

The change event occurs when you leave an input field after having changed its value. It doesn't fire immediately as the user changes the value, only when they've finished, which is detected by them using the keyboard or mouse to select a different element on the page.

The keyup event occurs after every keystroke. This allows you to take action while the user is typing.

The onChange event occurs when the value is assigned to the field, which is usually when the field loses focus.

The onKey events are bound to the keypress, meaning, they are triggered by the key itself and not related to the value assignment of the field.

The onKeyUp event will only fire when the user physically stops pressing the key (when the key goes "up").

You can test the behavior here .

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