我創建了一個帶有多個複選框的表單,我想將選中的複選框的值設置爲「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