Reputation: 331
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:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1" >
</body>
</html>
Javascript:
var x = document.getElementById("sc1dc1").value;
x.onchange = test;
function test(){alert("Test")};
Upvotes: 0
Views: 61
Reputation: 44107
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:
x.oninput = test;
You also need to make x
equal to the actual element, not the value of the element. Removing:
.value
From this line:
var x = document.getElementById("sc1dc1").value;
Will fix it.
Demonstration with onchange
:
var x = document.getElementById("sc1dc1");
x.onchange = test;
function test() {
alert("Test")
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1">
</body>
</html>
Demonstration with oninput
:
var x = document.getElementById("sc1dc1");
x.oninput = test;
function test() {
alert("Test")
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1">
</body>
</html>
Upvotes: 1
Reputation: 89264
You need to assign the function test
to the element's oninput
attribute. x
should be the HTMLInputElement
, not the value of the element.
Change
var x = document.getElementById("sc1dc1").value;
To
var x = document.getElementById("sc1dc1");
Use oninput
instead of onchange
if you want to trigger your event handler right when text is entered and not after the input loses focus.
var x = document.getElementById("sc1dc1");
x.oninput = test;
function test(){alert("Test")};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1" >
</body>
</html>
Upvotes: 0
Reputation: 127
The javascript should be this:
var x = document.getElementById("sc1dc1");
x.onchange = test;
function test(){alert("Test")};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1" >
</body>
</html>
You don't need .value
Upvotes: 0