【问题标题】:Comparing the Values of Two HTML Forms using JavaScript使用 JavaScript 比较两个 HTML 表单的值
【发布时间】:2020-02-24 21:06:29
【问题描述】:

我有两个具有相同属性的单独表单。有没有一种雄辩的方法可以使用 JS/Jquery 比较它们的值是否相等?

$('#form1').context.forms[0] === $('#form2').context.forms[0] 似乎有效,但我想知道是否有更好的方法。

我正在使用 spring/thymeleaf 来生成表单的内容。

【问题讨论】:

  • 我看不出这种比较是如何起作用的。它不是比较表单的内容,它只是判断它们是否是同一个 DOM 元素。
  • 你可以使用$("#form1').html() === $('#form2').html()
  • 看来我目前的解决方案不正确,总是会返回 true。
  • 它应该总是返回 false。
  • 您要比较 HTML 内容还是输入值?

标签: javascript jquery html spring thymeleaf


【解决方案1】:

在您的示例中,context 是整个document,因为这是您不将context 参数传递给$(selector, context) 时的默认值。所以你的代码基本上是这样做的:

document.forms[0] === document.forms[0] // Always true

如果要比较这些表单中的字段值,可以使用.serialize()

$('#form1').serialize() === $('#form2').serialize() // Implies fields are in the same order

演示

$('button').click(function() {
  var identical = $('#form1').serialize() === $('#form2').serialize();
  alert(identical ? "Values are identical" : "Values are NOT identical");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form1">
  <label>Name</label>
  <input name="name">
  <label>
    <input type="checkbox" name="accepts_tou">
    Do you accept out Terms of use?
  </label>
</form>
<form id="form2">
  <label>Name</label>
  <input name="name">
  <label>
    <input type="checkbox" name="accepts_tou">
    Do you accept out Terms of use?
  </label>
</form>

<button>Compare</button>

【讨论】:

  • 这很漂亮
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多