如何为未选中的复选框指定值

时间:2016-08-30 18:58:21

标签: javascript jquery html forms

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

这是我发现的:

$(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()
));

为什么脚本不起作用?

4 个答案:

答案 0 :(得分:2)

  1. 您需要查看jQuery API文档
  2. $.find它需要函数回调,这里可能不需要。

    this接受函数回调,它将在表单提交之前调用。

    无需在this

    中包裹选择器
    1. 您需要弄清楚$(this).attr("name")
    2. 的背景

      this中的$(this)[0].form指的是输入框

      forms中的document.forms仍然是输入框

      我想您正在尝试获取http.createServer()的引用。您可以使用.listen()

答案 1 :(得分:0)

您需要使用$(this)更改输入。在 .each 函数中,$(this)将引用复选框本身。

答案 2 :(得分:0)

使用相同名称的多个输入是正常的,您可以将值直接放在复选框

 $(this).find($("input:checkbox:not(:checked)")).each(function(){
    $(this).val($(this).is(':checked') ? "yes" : "no")
 })

答案 3 :(得分:0)

我能够使用这个更简单的脚本。效果很好。

$('#foo').click(function () {
    $(this).find('input[type="checkbox"]').each( function () {
        var checkbox = $(this);
        if( checkbox.is(':checked')) {
            checkbox.attr('value','yes');
        } else {
            checkbox.after().append(checkbox.clone().attr({type:'hidden', value:'no'}));

        }
    });
});