I have 5 text field in 5 rows like this..
<div class="dt_distance_slab">
<g:textField class ="number distanceSlab1" name="distanceSlabCost1" id = "distanceSlabCost1" value=""/>
</div>
<div class="dt_distance_slab">
<g:textField class ="number distanceSlab2" name="distanceSlabCost2" id = "distanceSlabCost2" value=""/>
</div>
<div class="dt_distance_slab">
<g:textField class ="number distanceSlab3" name="distanceSlabCost3" id = "distanceSlabCost3" value=""/>
</div>
<div class="dt_distance_slab">
<g:textField class ="number distanceSlab4" name="distanceSlabCost4" id = "distanceSlabCost4" value=""/>
</div>
<div class="dt_distance_slab">
&l开发者_如何学运维t;g:textField class ="number distanceSlab5" name="distanceSlabCost5" id = "distanceSlabCost5" value=""/>
</div>
here all fields are optional.. i want to put validation like if user wants to enter the value.. he cannot skip a row in between ... if he want to enter value for a text field ,previous text field must have value..
validation will be done on submitting the form
Would you get a better user experience by preventing input in the fields that doesn't have a preceeding value? If all the fields except the first one is disabled by default, you could enable the next one on the blur event.
$('input:gt(1)').attr('disabled','disabled');
var fields = $('input');
$('input').blur(function(){
var $this = $(this);
if($this.val() != ''){
fields.eq($this.index()+1).attr('disabled','');
}
});
Try with this code:
$(document).ready(function(){
//assuming the validation fires on the click of a button
$("#btnSubmit").click(function(){
//set valid variable to true
var blnIsValid = true;
//loop through each of the text boxes
$(":text[class^='number']").each(function(i){
//start validating from the second text box
if(i > 0) {
var curTxtBox = $(this);
var prevTxtBox = $(":text[class^='number']:eq("+ (i-1) +")");
if($.trim(curTxtBox.val()) != "" && $.trim(prevTxtBox.val()) == "") {
alert("Enter value for previous distance");
//set focus on the text box
prevTxtBox.focus();
//set valid variable to false
blnIsValid = false;
//exit the loop
return false;
}
}
});
return blnIsValid;
});
});
Here's a working example in jsFiddle
Borrowing heavily from jSang's answer and I'd do it like this:
$(document).ready(function(){
//assuming the validation fires on the click of a button
$("#btnSubmit").click(function(){
var haveEmpty = false;
var blnIsValid = true;
$(":text[class^='number']").each(function(i){
if( $(this).val() != "" )
{
if( haveEmpty )
{
blnIsValid = false;
//need to do something to let the user know validation failed here
}
}
else
haveEmpty = true;
});
return blnIsValid;
});
});
精彩评论