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>
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
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.
Value is there. But it is just a JS string. It has no backward binding to the DOM element.