onchange property doesn`t work in javascript

Tags: , ,



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")};

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:

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>


Source: stackoverflow