简体   繁体   中英

Input value won't change

I'm having some trouble getting my input value to change when I type a value inside it.

 var t = document.createElement('div'); t.innerHTML = '<input type="text" id="myText">'; document.getElementById("news").appendChild(t); var x = document.getElementById("myText").value; //Grabs the value of the input. t.onchange = function(){myFunction()} //Input. Onchange.. function myFunction() { console.log(x); //Logs the value of "x" } 

My problem is when I type some string in the input. "Hello world" as a example. It should print "Hello world" to the console. Instead it prints nothing. Just a blank line. How could I make it to print what I type inside the input box?

Using my script.

  1. The 'change' event fires only when you leave the input field. You probably want an 'input' event here which fires immediately and the listener is registered with oninput
  2. x is a variable that's initialized just once and variables are not bound to the current value of whatever you used to initialize them so you need to read the element's value again
  3. bind a function directly to the the event so it can use this to access the element directly
  4. add the event on the input element, not on the div

document.getElementById("myText").oninput = myFunction;

function myFunction() {
  console.log(this.value)
}

Since we don't have onchange on div, it's on input element.

Difference between onchange & onkeyup . (MDN)

onkeyup — The keyup event fires when the user releases a key that was previously pressed.

So, whenever you change value it gets triggered.

onchange — change events fire when the user commits a value change to a form control. This may be done, for example, by clicking outside of the control or by using the Tab key to switch to a different control.

So, unless you tab or click outside of input your function won't get called.

You should replace your code with following.

 var t = document.createElement('div'); t.innerHTML = '<input type="text" id="myText">' document.getElementById("news").appendChild(t); var input = document.getElementById('myText'); input.onkeyup = myFunction function myFunction() { var x = document.getElementById("myText").value; //Grabs the value of the input. console.log(x); //Logs the value of "x" } 
 <div id="news"/> 

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