文本字段验证使用Jquery

时间:2011-09-02 12:04:17

标签: jquery gsp

我有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>

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

将在提交表格

时进行验证

3 个答案:

答案 0 :(得分:6)

通过阻止没有前置值的字段中的输入,您是否可以获得更好的用户体验?如果默认情况下禁用除第一个以外的所有字段,则可以在模糊事件上启用下一个字段。

$('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','');
  }
});

答案 1 :(得分:4)

尝试使用此代码:

$(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

中的一个工作示例

答案 2 :(得分:2)

从jSang的答案中大量借用,我会这样做:

$(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;
    });
});