Javascript 使用脚本创建隐藏的输入字段

Javascript 使用脚本创建隐藏的输入字段,javascript,jquery,html,forms,Javascript,Jquery,Html,Forms,我有一个带有多个复选框的表单。选中时,提交时该值将为“是”。我试图找到最好的方法,在提交表单时将值“no”分配给所有未选中的复选框 我好像没法让它工作。以下是我所拥有的: $('#foo :checkbox').submit(function() { var $this = $(this); // $this will contain a reference to the checkbox if ($this.is('not(:checked)')) { // the

我有一个带有多个复选框的表单。选中时,提交时该值将为“是”。我试图找到最好的方法,在提交表单时将值“no”分配给所有未选中的复选框

我好像没法让它工作。以下是我所拥有的:

$('#foo :checkbox').submit(function() {
  var $this = $(this);
  // $this will contain a reference to the checkbox   
  if ($this.is('not(:checked)')) {
    // the checkbox was not checked 
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", $(this).attr("name"));
    input.setAttribute("value", "no");
    //append to form element that you want .
    document.getElementById("#foo").appendChild(input);
  } else {

  }
});
为什么不工作?

来自

当用户尝试提交时,提交事件被发送到元素 提交一份表格。它只能附加到
元素

因此,您只能将事件附加到窗体,而不能附加到复选框

这意味着您的代码实际上甚至不会运行

据我所知,以上回答了你的问题(即它说明了为什么不起作用)

以下是一些可能有效的方法:

$('#foo').submit(function() {
  var $this = $(this);
  // $this will contain a reference to the form
  $this.find(':checkbox' ... // your code here

根据另一个答案

该事件在表单上触发,因此:

$('form').submit(function() {
    var $this = $(this);

    // Set checked inputs to value yes
    $this.find('input:checkbox:checked').attr('value', 'yes');

    // Set unchecked inputs to value no
    $this.find('input:checkbox:not(:checked)').attr('value', 'no');
});
将在触发提交时触发

假设HTML类似于:

<form>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="submit" />
</form>


您应该使用
。click()
,而不是
。submit()
@barmar如果我使用click,未选中的复选框将不会遵循此规则,因为它们从未被单击过。我误解了这个问题。逐步浏览您的代码或至少在其中放置一个
控制台总是很好的。登录
,以确保它按照您的预期进行操作。是的,Chris,
submit
事件需要绑定到
表单
元素。它会运行,但不会做任何有用的事情,因为
submit
事件从未触发过。我怀疑函数中的代码是否会按显示的方式运行。那么应该是这样的吗?如果这是正确的,我如何使用与它正在选中的当前复选框相同的名称?未选中的复选框不会与表单一起提交。因此,更改它们的值仍然不会将它们包含在提交中。我尝试了此解决方案,没有看到未选中框的“否”值。似乎是因为它们没有被检查,所以它们从未被提交。