0

I have the following code

//main.js
var textinput = document.getElementById('textinput').value;

function textChanger() {
  setTimeout(function() {
    textinput = 'newtext';
  }, 3000);
}
<!doctype html>
<html>

<head>
  <title> some title </title>
</head>

<body>
  <input type="text" value="sometext" id="textinput" oninput="textChanger()">
  <script type="text/javascript" scr="main.js"></script>
</body>

</html>

I expect that the value of textinput should be changed after 3 seconds but it isn't changing.

Croximo Crox
  • 79
  • 10
  • Does this answer your question? [Set the value of an input field](https://stackoverflow.com/questions/7609130/set-the-value-of-an-input-field) – Charlie Jul 03 '20 at 15:55

2 Answers2

0

You should change the value property of the input.

var textinput = document.getElementById('textinput');

function textChanger() {
   setTimeout(function() {
      textinput.value = 'newtext';
   }, 3000);
}


textChanger();
<input type="text" value="sometext" id="textinput" oninput="textChanger()">

You can find lot of details here:

Set the value of an input field

Charlie
  • 22,886
  • 11
  • 59
  • 90
0

That happens because you are copying the text from the <input> to the variable. Unlike objects, primitives (like strings) are passed by value. That means that when you update the variable, you are not updating the <input> value.

This code works:

var inputElement = document.getElementById('textinput');

function textChanger() {
  setTimeout(function() {
    inputElement.value = 'newtext';
  }, 3000);
}
<!DOCTYPE html> <!-- Don't forget the doctype! -->
<html>

<head>
  <title> some title </title>
</head>

<body>
  <input type="text" value="sometext" id="textinput" oninput="textChanger()">
  <script type="text/javascript" scr="main.js"></script>
</body>

</html>
D. Pardal
  • 6,173
  • 1
  • 17
  • 37