Problem Statement
Write a HTML page holding a form and a text field. Using JavaScript make the text field to accept numbers only. When a non-number character is entered through the keyboard (or by any other way), make the field red for a while and do not accept the change (preserve the previous value of the field).
Expected Output
Solution
<!DOCTYPE html>
<html>
<head>
<title>Text field</title>
<meta charset="UTF-8">
<script type="text/javascript">
window.onload = function(){
document.formex.numberinput.onchange = checkIfNumber;
function checkIfNumber(){
if (isNaN(parseInt(document.formex.numberinput.value, 10))){
document.formex.numberinput.innerHTML = document.formex.numberinput.value;
document.formex.numberinput.readOnly = true;
setTimeout(function(){
document.formex.numberinput.readOnly = false;
}, 10000);
}
}
}
</script>
<style type="text/css">
input[readonly] {
background-color: red;
}
</style>
</head>
<body>
<form name="formex">
<input type="text" name="numberinput">
</form>
</body>
</html>
Above code uses name attributes as element lookup approach.
Can we improve this code?
.read-only
would be better, then you could use it on other read-only elements, which could include any form element \$\endgroup\$