【问题标题】:jquery - multiple forms in a page - check for empty field in a different form from the one submittedjquery - 一个页面中的多个表单 - 检查与提交的表单不同的表单中的空字段
【发布时间】:2016-01-27 16:44:28
【问题描述】:

我有两种不同的表单,在使用#orchestrationForm 提交表单时,我想查看#blah 表单中的filePaths 文本框是否为空。如何在 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 有什么问题?

【问题讨论】:

  • noFiles 仅保留最后检查的文件输入字段的值。您在每次迭代时都覆盖它。

标签: jquery forms http-post


【解决方案1】:

不清楚您在做什么,但我怀疑您正在构建表单以上传多个文件。我创建了一个工作示例: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() 在这两种情况下都等于 true。使用$(this).val() === "",这样当它不为空时,它会返回false。在我的示例中,空字段提供警报,非空字段不会提供警报,但由于return false,表单会失败。

【讨论】:

  • 这就是我想要的。谢谢你。为什么 $(this).val() === "" 与 !$(this).val() 不同?我明白 === 是为了严格比较。
  • 我必须研究它,但是,!$(this).val() 返回true,无论目标中的内容如何。将值与“”与===== 进行比较,每次都会得到truefalse 结果。
  • 看看这个:jsfiddle.net/Twisty/n53qg34t 所以也许这与.each() 处理$(this) 的方式有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 2021-05-18
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多