Search code examples
jquerygsp

Text field validation Using Jquery


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">
     <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


Solution

  • 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