我创建了一个带有多个复选框的表单,我想将选中的复选框的值设置为“yes”,未勾选的复选框的值设置为“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()
));
为什么不工作的脚本?
准备处理程序的Ypur synthax是错误的,检查任何基本的例子。顺便说一句,你的缩进是awfull,让你的代码不可读 –
这是什么意思'var form = $(this)[0] .form' ... forms有一个.form属性? – cuniculus
这需要大量的调试......在每个点输出具有变量值的控制台消息是很好的,以查看您的函数是否正在运行以及变量是否获得您期望的值。 – cuniculus