当所有输入文本字段都为空时,禁止表单提交,但当jquery中的任何字段不为空时允许提交

prevent form submission when all input text fields are empty but allow submission when any of them in not empty with jquery

本文关键字:字段 任何 提交 许提交 表单提交 输入 文本 但当 禁止 jquery      更新时间:2023-09-26

场景是我有一个具有动态多文本字段的表单。

<form id="add" action="" method="POST">
  <input type="text" id="product-$id" name="quantity[]" class="quantity" />
</form>

根据条件,它生成多个输入字段。看起来像这个

<form id="add" action="" method="POST">
<input type="text" id="product-1" name="quantity[]" class="quantity" />
<input type="text" id="product-2" name="quantity[]" class="quantity" />
<input type="text" id="product-3" name="quantity[]" class="quantity" />
    </form>

现在,如果所有文本字段都为空,我想阻止提交表单。但如果其中任何一个有价值,我会允许提交表格。

我希望下面的代码能让您了解如何继续。

function SubmitForm(){
     //get all the dynamic textbox in the form
      var quantities =$('#add').find('.quantity');
      var hasValue = false;
      $.each(quantities, function(i, txtbox)
        {
           if ($.trim($(txtbox).val()) != '')
             {
               hasValue = true;
               return false; //break
               }
        });
        if (!hasValue)
          {
            return; //do not proceed further
            }
      //code here as atleast one textbox has a value
}