I want to launch the function test()
if the user inputs something in the html input field with the id="sc1dc1"
(without using the "onchange="
directly in HTML). What is wrong?
HTML:
JavaScript
x
10
10
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title></title>
5
</head>
6
<body>
7
<input type="text" id="sc1dc1" >
8
</body>
9
</html>
10
Javascript:
JavaScript
1
4
1
var x = document.getElementById("sc1dc1").value;
2
x.onchange = test;
3
function test(){alert("Test")};
4
Advertisement
Answer
The thing about onchange
events is that they only fire when the <input>
field loses focus. If you want an immediate response, you should use oninput
like so:
JavaScript
1
2
1
x.oninput = test;
2
You also need to make x
equal to the actual element, not the value of the element. Removing:
JavaScript
1
2
1
.value
2
From this line:
JavaScript
1
2
1
var x = document.getElementById("sc1dc1").value;
2
Will fix it.
Demonstration with onchange
:
JavaScript
1
6
1
var x = document.getElementById("sc1dc1");
2
x.onchange = test;
3
4
function test() {
5
alert("Test")
6
};
JavaScript
1
12
12
1
<!DOCTYPE html>
2
<html>
3
4
<head>
5
<title></title>
6
</head>
7
8
<body>
9
<input type="text" id="sc1dc1">
10
</body>
11
12
</html>
Demonstration with oninput
:
JavaScript
1
6
1
var x = document.getElementById("sc1dc1");
2
x.oninput = test;
3
4
function test() {
5
alert("Test")
6
};
JavaScript
1
12
12
1
<!DOCTYPE html>
2
<html>
3
4
<head>
5
<title></title>
6
</head>
7
8
<body>
9
<input type="text" id="sc1dc1">
10
</body>
11
12
</html>