0

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")};
1
  • 3
    First: you take the value of the element, and then address its onchange attribute. That is wrong. The value does not have that property. You need to remove .value. Also, onchange only fires when you leave the input field. If you want immediate response then use oninput instead of onchange. Commented Dec 27, 2018 at 23:04

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.