文本字段验证使用Jquery

前端之家收集整理的这篇文章主要介绍了文本字段验证使用Jquery前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有5行的文本字段有5个这样的..
<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>

这里所有的字段都是可选的..我想放置验证,如果用户想要输入的值..他不能跳过一行之间…如果他想输入一个文本字段的值,上一个文本字段必须有值. .

验证将在提交表单时进行

解决方法

尝试使用此代码
$(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;
    });
});

这是jsFiddle的一个例子

原文链接:https://www.f2er.com/jquery/179255.html

猜你在找的jQuery相关文章