javascript validation
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
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
Do something like this in client side javascript.
if (document.getElementById('val1').value.length <= document.getElementById('val2').value.length)
精彩评论