简体   繁体   中英

JavaScript document.getElementById().value not working

For a school project I have to replace words in a string. Using the .split() and .join() method. that works fine but I'm having problems with document.getElementById().value; Whenever I put words in my Input it just returns a empty string. Any help?

<input type="text" id="word"/>

//JavaScript
var newWord = document.getElementById("word").value;
console.log(newWord);

Ensure to add an event handler.

Add an onchange event listener to input element.

 function func() { var newWord = document.getElementById("word").value; console.log(newWord); }
 <input type="text" id="word" onchange='func()'/>

You will need to enter a value to your input or add a default value

<input type="text" id="word" value="Hello"/>

var newWord = document.getElementById("word").value;
console.log(newWord);

This will log the value

Use .addEventListener to run a function when a change event is fired - This will run your function whenever the value in the input is updated and the focus is removed from the input box

 document.getElementById('word').addEventListener('change', function () { let newWord = this.value; console.log(newWord); });
 <input type="text" id="word"/>

Or, you could use the input event, which will fire as soon as the input is changed

 document.getElementById('word').addEventListener('input', function () { let newWord = this.value; console.log(newWord); });
 <input type="text" id="word"/>

I cannot get your question, but according to my understanding, you need to use a function to get the value of input box, when an event occurs. here is the code something like this.

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" id="myinput" onkeypress="myFunction()">

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById('myinput').value;
  document.getElementById('demo').innerHTML = x;
}
</script>

</body>
</html>

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