我正在创建一个包含多个复选框的表单,我希望将选中的复选框的值设置为"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()
));
为什么脚本不起作用?
最佳答案
- 您需要查看 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/