Javascript to validate two text boxes
I have two text boxes.
One text box is min and other text box is max.
I want to make sure that the 开发者_如何学运维user enters a greater value in the max text box compared to the min text box.Also the case might be handled if the user enters one text box is about to enter the next text box .How can i do this job effeciently.
The simplest way would be to assign the value to a variable and test them :
function checker(){
var min = document.getElementById("min").value ;
var max = document.getElementById("max").value ;
if(min > max){
alert('min is more than max');
}
}
Then add checker to a onchange
on the inputs:
<input type='text' id='min' onchange='checker();' />
<input type='text' id='max' onchange='checker();' />
First, you'll want to store the two text box elements in variables so you can access their values later:
var min = document.getElementById('min'),
max = document.getElementById('max');
Then, you'll need a function to validate the two boxes. This function should not run unless both boxes contain a value (to avoid the case you mentioned where the user hasn't yet filled in both boxes).
function validate() {
if (!min.value || !max.value) {
return;
}
// ... do the validation
}
For the actual validation inside the function, you'll need to take the text strings inside the input boxes and parse for numeric values. Once you have the two numbers, you can compare their values and alert the user if there was a problem:
function validate() {
var minValue, maxValue;
if (!min.value || !max.value) {
return;
}
minValue = parseFloat(min.value);
maxValue = parseFloat(max.value);
if (minValue >= maxValue) {
alert('Min Value must be smaller than Max Value!');
}
}
The last thing to do is decide when to run this function. You'll probably want it to run when either of the text boxes loses focus (onblur).
min.onblur = validate;
max.onblur = validate;
For a complete working example, see this fiddle.
http://jsfiddle.net/kYXsU/
The function will be called when the the user leaves the min textbox... If the value of min is larger than max a pop-up will occur. (You don't have to use a pop-up but it's up to you).
<html>
<head>
<title>Hey</title>
</head>
<body>
<label for="max">Max</label>
<input id="max" />
<label for="max">Min</label>
<input id="min" />
<body>
</html>
//use Jquery
$('#min').blur(function() {
if ($('#min').val() > $('#max').val())
{
alert('Min cannot be bigger than max');
}
});
精彩评论