jquery - 页面中的多个表单 - 检查与提交的表单不同的空字段

时间:2016-01-27 16:44:29

标签: jquery html-form-post

我有两种不同的表单,在使用#orchestrationForm提交表单时,我想查看带有filePaths的表单中的#blah文本框是否为空。如何在jquery中执行此操作?

我的HTML和jquery如下:

<form id="blah"></form>
<form method="POST" action="/api/wand" enctype="multipart/form-data" id="orchestrationForm">
  <section id="data-files">
    <input type="text" class="form-control" name="filePaths" form="blah" />
  </section>
</form>

$("#orchestrationForm").on("submit", function() {
  var noFiles = false;
  $("[name='filePaths']", this).each(function() {
    if (!$(this).val()) {
      noFiles = true;
    }
  });
  if (noFiles) {
    alert("Upload atleast one file");
  }
  return false;
});

在提交我的业务流程表单时,我按filePaths的名称属性进行搜索,如果它们是空的,则显示一个警告框。问题是,即使filePaths文本框不为空,noFiles的计算结果为true,也会显示警告框。我的jquery有什么问题?

1 个答案:

答案 0 :(得分:0)

您不清楚自己在做什么,但我怀疑您正在构建表单以上传多个文件。我创建了一个工作示例:https://jsfiddle.net/Twisty/p75tzcvj/

<强> HTML

<form id="blah">
  <h2>
  Form 1
  </h2>
</form>
<form method="POST" action="/api/wand" enctype="multipart/form-data" id="orchestrationForm">
  <h2>
  Form 2
  </h2>
  <section id="data-files">
    <input type="text" class="form-control" name="filePaths" form="blah" />
  </section>
  <button type="submit">Upload</button>
</form>

<强> JQuery的

$(document).ready(function() {
  $("#orchestrationForm").on("submit", function() {
    var noFiles = false;
    $("input[name='filePaths']", this).each(function() {
      if ($(this).val() === "") {
        noFiles = true;
      }
    });
    if (noFiles) {
      alert("Upload atleast one file");
    }
    return false;
  });
});

如果该字段为空,则会显示警报。在这两种情况下,!$(this).val()等同于真。使用$(this).val() === "",这样当它不为空时,它将返回false。在我的示例中,空字段提供警报,非空字段不提供警报,但由于return false,表单失败。