I have two input fields say val1 and val2 in jsp.Let say val1 is dynamic, I need to restrict user entering the value of val2 not exceeding val1. It can be equal but not more. I tried with onKeypress but i was not able to success. Val1 value can be get from document.getElementById(..).value. Can anyone tell me the efficient way to do this. Thanks
+1
A:
Use the onChange
event.
<script>
function checkValues(in) {
var val1 = getElementById(val1);
var val2 = getElementById(val2);
// Don't check if values are missing
if (val1.value == "" || val2.value == "") return;
// Don't allow val2 to be greater than val1
if (parseInt(val1.value)
> parseInt(val2.value)) {
// Try not to use an alert, replace this with an in-page warning.
alert("Value 2 must be greater than Value 1.");
in.value = "";
}
}
</script>
<input type="text" id="val1" onChange="checkValues(this)" />
<input type="text" id="val2" onChange="checkValues(this)" />
Note that this doesn't fully stop a user from submitting an invalid value. You should also verify the values on the server
Ben S
2010-06-22 16:25:10
So that means , there no way in javaScript to restrict the user so that the user cannot enter greater val2 than val1.
2010-06-22 16:41:09
Exactly. If a user turns off javascript, they can enter any value they want.
Ben S
2010-06-22 17:01:28
A:
Do something like this in client side javascript.
if (document.getElementById('val1').value.length <= document.getElementById('val2').value.length)
Shane
2010-06-22 16:25:16
Comparing the length isn't what he's looking for `7` is greater than `3`, but your solution allows that.
Ben S
2010-06-22 16:35:29
Oh I see, must have misread... Bit harsh voting me down there somebody :-)
Shane
2010-06-22 16:40:29
Didn't vote down. I chose to comment instead. Sorry if my comment caused you to get voted down :|
Ben S
2010-06-22 17:01:10