我可以在jquery中为函数循环使用相同的返回值

时间:2013-11-13 13:31:46

标签: javascript jquery

我对函数的返回值有点困惑。我有一个表格,里面有文字框和单选按钮。我正在一起验证所有文本框和单选按钮。所以我现在从这两个函数中得到2个返回值。我可以为这两个函数使用相同的返回变量。 这是我的代码

$(function() {
$('#submitBtn').click(function(){
    var returnValue = true;
    //Validating radio buttons required
    //Code of checking radio buttons
        if( !unchecked.is(':checked') ) {
            alert("Required field");
            returnValue = false;
        }
    });

    //Other Required fields

    $('.required_text').filter(':visible').each(function () {
        var input = $(this);
        if (!$(this).val()) {
            alert("Required field");
            returnValue = false;
        }
    });
    alert(returnValue);
    return returnValue;
});

}
});

如果我为这些函数使用不同的返回变量,如radioReturn和textReturn,如果我使用

,则使用最后一个
if(radioReturn && textReturn){
returnValue = true;
}
else{
returnValue = false;
}

但我不想使用太多变量。那么有什么方法我只能使用一个返回变量并处理表单提交。

由于

1 个答案:

答案 0 :(得分:0)

是的,你可以

试试这个

$(function() {
    // all validation inside the click event
    $('#submitBtn').click(function(){
      // initiate the value as true
      var returnValue = true;
      //Validating radio buttons required
      //Code of checking radio buttons
      if( !unchecked.is(':checked') ) {
        alert("Required field");
        // add css to highlight error
        returnValue = false;
      }
      // check the input fields only if returnValue is true
      // if u want to highlight  all the errors then this check no need
      if(returnValue)
      {
        $('.required_text').filter(':visible').each(function () {
           var input = $(this);
           if (!$(this).val()) {
              // add css to highlight error
              alert("Required field");
           returnValue = false;
           }
         });
      }
      //Other Required fields

      alert(returnValue);
      return returnValue;
});


});

更新2:

  $('#submitBtn').click(function(){
       // initiate the value as true
       var returnValue = true;


       //Validating radio buttons required
       //Code of checking radio buttons
       if( !unchecked.is(':checked') ) {             
         // add css to highlight error or
         // add label nearby it to said Required
         returnValue = false;
        }

        // check the input fields only if returnValue is true
        // if u want to highlight  all the errors then this check no need
        $('.required_text').filter(':visible').each(function () {
          var input = $(this);
          if (!$(this).val()) {
             // add css to highlight error or
             // add label nearby it to said Required
           returnValue = false;
        }
      });

      //Other Required fields

      // here if u have any errors then the return value always false
      alert(returnValue);
      return returnValue;
  });