简体   繁体   中英

What event to know when user has entered data into form?

I have a HTML form. I want to enable/disable a button until user eneters text in one of the fields. I am adding an event attribute to the which triggers some javascript. This javascript will enable/disable the button. Problem is I can't figure out what event attribute to use. What event attribute please will trigger as soon as user enters data? I tried onchange but that only gets called when i clicked back outside the text area. So it may aswell be onblur.

You can use the input

function activateForm (event) {
    if(!this.value == ""){ 

    }
}
var input = document.querySelector(".myInput");

input.addEventListener("input", activateForm , false)

There are 2 possible events that can be used: either onChange or onKeyPress . onChange will trigger when the value of an input has changed while onKeyPress will trigger every time the user types something in a text box. The onChange triggers once the user has CHANGED something in the value, and got out of the input focus. That means the user has to hit TAB or click somewhere else for the event to trigger, hence why onKeyPress might be better suited.

Read more:

http://www.w3schools.com/jsref/event_onchange.asp http://www.w3schools.com/jsref/event_onkeypress.asp

Younger browsers also support onInput which should certainly be prefered for now, if you do not need to support older browsers.

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