Reputation: 610
I have some troubles to validate user input while they are typing.
For example: the valid range is 600-800 and user is trying to type 700
When textbox is empty: show nothing
When textbox is 7: show red
When textbox is 70: show red
When textbox is 700:show nothing
I hope I can do it in js, can anyone help me?
Upvotes: 6
Views: 19501
Reputation: 7261
You could use both the input
and change
events. Input will fire when a key press results in a character input. Change will fire when the focus of the text field is lost after the value of the field has changed, and I think in most browsers also after text is pasted into it from the clipboard.
document.getElementById('validate').addEventListener('input', pressHandler);
document.getElementById('validate').addEventListener('change', pressHandler);
Upvotes: 0
Reputation: 724
Here is another example, looks like your question was already answered as I was writing this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<style>
.red {
background-color: red;
}
</style>
</head>
<body>
<form id="myForm">
<input type="text" id="validate" class=""/>
</form>
<script>
function pressHandler(e) {
console.log(this.value);
if (parseInt(this.value) <= 700) {
this.className = "red";
} else {
this.className = "";
}
}
document.getElementById("validate").addEventListener("keyup",pressHandler);
</script>
</body>
</html>
Upvotes: 1
Reputation: 1949
Here is an example:
<input type="text" id="myTextBox" onKeyUp="checkInput()" />
<script>
var myTextBox = document.getElementById('myTextBox');
function checkInput() {
var value = myTextBox.value;
if (!value || isNaN(value) || parseInt(value, 10) < 700 || parseInt(value, 10) > 800) {
myTextBox.style.backgroundColor = 'red';
} else {
myTextBox.style.backgroundColor = 'green';
}
}
</script>
Upvotes: 5
Reputation: 150
Sounds like you are using the onchange event.
If you try onkeypress it should do what you are after.
Upvotes: 0