【问题标题】:jQuery required fields loop. based on CSS classjQuery 必填字段循环。基于 CSS 类
【发布时间】:2013-11-19 21:55:55
【问题描述】:

我正在尝试找出一种基于<input class="required"> 循环遍历以下必填字段的方法。目前我只评估循环中的第一个输入。我如何在这里使用循环来横穿 dom 并检查所有输入框?谢谢你。我见过类似的例子,在我的具体情况下,我似乎无法让它们工作。

$("#howMuch").click(function () {
    var numOfPeriods = 0;
    //Validates for empty code only. 
    if ($('.required').val().length == 0) {
        $('.modal').show();
        $('.modal_content').text('Please fill in the Required Fields');
    } else {
        //Clear previous graph
        clearGraph();
        //Adjust the number of periods from years to month
        numOfPeriods = yearToMonthAdj();
        //Declare a variable for the final future value
        var futureValue = createiRateGraphNoInterest(numOfPeriods);
        //Test if were rich
        testFVforMillionaire(futureValue);
    }
});

【问题讨论】:

    标签: javascript jquery css loops


    【解决方案1】:

    你可以使用 .each() 在你的元素中循环使用 required
    试试这个:

    $('.required').each(function(index){
       if($(this).val().length==0) {
           $('.modal').show();
           $('.modal_content').text('Please fill in the Required Fields');
       } else {
          //Clear previous graph
          clearGraph();
          //Adjust the number of periods from years to month
          numOfPeriods = yearToMonthAdj();
          //Declare a variable for the final future value
          var futureValue = createiRateGraphNoInterest(numOfPeriods);
          //Test if were rich
          testFVforMillionaire(futureValue);
      }
    });
    

    【讨论】:

    • 感谢您的帮助。但是,这仅在两个输入框均为空白时才有效。如果填写了两个输入框之一,则允许该值退出循环并填充图形的轴。你知道如何解决这个问题吗?
    • 为了解决第二个问题。我添加了 return false;波纹管 $('.modal_content') 以确保一旦找到一个空字段,它就会从函数中取消
    • 您可以创建一个 var,如果某些复选框为空白,则将 var 设置为 0。毕竟循环检查 var 是否与 0 不同意味着所有复选框都已填充 l。否则意味着某些复选框是空白的@surgentt
    【解决方案2】:

    您可以使用 .each() 遍历所有元素:

    $(".required").each( function() {  } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多