javascript - 如何为未选中的复选框分配值

标签 javascript jquery html forms

我正在创建一个包含多个复选框的表单,我希望将选中的复选框的值设置为"is",将未选中的复选框的值设置为“否”。我托管表单的网站不允许我添加具有相同名称和不同值的隐藏字段,因此我必须找到在提交时添加隐藏复选框并包含“否”值的脚本。目前,当我提交表单时,未选中的框将记录为未定义,但出于数据目的,我需要将其填写为“否”。

这是我发现的:

$(document).ready($("#foo").submit(
  function() {

    // Add an event listener on #foo submit action...
    // For each unchecked checkbox on the form...
    $(this).find($("input:checkbox:not(:checked)")).each(

      // Create a hidden field with the same name as the checkbox and a value of 0
      // You could just as easily use "off", "false", or whatever you want to get
      // when the checkbox is empty.
      function(index) {
        var input = $('<input />');
        input.attr('type', 'hidden');
        input.attr('name', $(this).attr("name")); // Same name as the checkbox
        input.attr('value', "no"); // or 'off', 'false', 'no', whatever

        // append it to the form the checkbox is in just as it's being submitted
        var form = $(this)[0].form;
        $(form).append(input);

      } // end function inside each()
    ); // end each() argument list

    return true; // Don't abort the form submit

  } // end function inside submit()
));

为什么脚本不起作用?

最佳答案

  1. 您需要查看 jQuery API 文档

$(document).ready(function(){});它需要函数回调,这里可能不需要。

$("#foo").submit接受函数回调,该函数将在提交表单之前调用。

无需将选择器包装在 $.find

  • 您需要弄清楚 this 的上下文
  • this$(this).attr("name")指的是输入框

    this$(this)[0].form依然是输入框

    我猜您正在尝试获取 forms 的引用。您可以使用document.forms

    关于javascript - 如何为未选中的复选框分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235141/

    相关文章:

    javascript - 输入按钮使用 svg 而不是文本

    jquery - 在 css 中添加 href 链接到 <a> 标签

    javascript - Flask - 我想要一种基于数据库数据显示任务流程图的方法

    javascript - JQuery 升序和降序排序(不是表格)

    javascript - 上传图片后隐藏kendo ui upload的消息

    HTML - 有序列表,将列表编号设置为 (a)、(i)、(aa)

    Javascript:以有状态的方式有效地替换具有指定值属性的数组中的对象?

    javascript - 运行并添加单元测试到nodejs项目

    javascript - 向 Phaser 3 游戏添加场景不起作用

    jquery - 有人可以解释一下这句话的意思吗