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

can I use same return value for function loops in jquery

本文关键字:返回值 jquery 循环 函数 我可以      更新时间:2023-09-26

我对函数的返回值有点困惑。我有一个表单,里面有文本框和单选按钮。我正在一起验证所有文本框和单选按钮。所以我现在有这 2 个函数的 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;
}

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

谢谢

是的,你可以

像这样尝试

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