jQuery需要字段循环。基于CSS类

时间:2013-11-19 21:55:56

标签: javascript jquery css loops

我试图找出一种基于<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);
    }
});

2 个答案:

答案 0 :(得分:2)

您可以使用.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);
  }
});

答案 1 :(得分:0)

您可以使用.each():

遍历所有元素
$(".required").each( function() {  } );