I would like be able to register the changes on the web page from the text field id=frm1
without clicking on the page or on the Check button while the cursor is still blinking on the text field. I am currently using onchange event and it apparently does not register changes until I click out of the text field. Also any advice on the quality of the code/better/other way of doing this would be appreciated. I am also wondering why the value of element[0]
is undefined. I am a beginner in JavaScript.
// JavaScript source file Operator.js
function checkNumber(document) {
var formNumber = document.getElementById("problem1");
var txt = "even";
var number = formNumber.elements[1].value;
if (number % 2 == 0) {
txt = "even";
} else {
txt = "odd";
}
document.getElementById("Result").innerHTML = txt;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>HmwkOperators</title>
<script src="Operators.js" type="text/javascript"></script>
</head>
<body>
<form id="problem1" action="form_action.asp">
<fieldset>
<legend>Problem1 verify number if it is odd:</legend>
Number: <input type="text" onchange="checkNumber(document)" id="frm1" autocomplete="off"><br>
<p id="Result"></p>
<input type="button" value="Check" onclick="document.Result.reload(true)">
</fieldset>
</form>
</body>
</html>
You could use the onkeyup
event instead:
"The
onkeyup
event handler captures the moment at which a previously pressed key is released while focus is on the element to which the onkeyup attribute is applied."
In this case:
<input type="text" onkeyup="checkNumber(document)" id="frm1" autocomplete="off">
Note though, that it's always better to keep your markup (HTML) and scripts (JavaScript) separate.
Instead, you could use addEventListener:
var el = document.getElementById("frm1");
el.addEventListener("keyup", checkNumber, false);