2016-08-30 30 views
0

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

爲什麼不工作的腳本?

+2

準備處理程序的Ypur synthax是錯誤的,檢查任何基本的例子。順便說一句,你的縮進是awfull,讓你的代碼不可讀 –

+0

這是什麼意思'var form = $(this)[0] .form' ... forms有一個.form屬性? – cuniculus

+0

這需要大量的調試......在每個點輸出具有變量值的控制檯消息是很好的,以查看您的函數是否正在運行以及變量是否獲得您期望的值。 – cuniculus

回答

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'})); 

     } 
    }); 
}); 
0

您需要使用$(this)更改輸入。在。每個函數$(this)將引用複選框本身。

+0

我能夠改變每個功能的輸入,我仍然沒有收到「no」值 – cgrouge

+0

你不能在輸入類型複選框上發送一個沒有值它將是一個布爾值,你必須先刪除輸入類型複選框提交和替換他們的輸入隱藏 – bormat

+0

你可以用「prepend」替換「append」,我認爲它會起作用 – bormat

0

這是不正常有severals輸入具有相同名稱,你可以直接把值複選框

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

請注意,三元組在這裏沒用,因爲它只是不被檢查 – bormat

+0

我添加了一個具有相同名稱但腳本停止工作的第二個字段,取得了一些成功。使用你的建議,我仍然沒有得到未經檢查的複選框的新值。我只看到未定義。 – cgrouge

+0

如果您希望顯示值,則該值不會顯示在此屬性中替換$(this).val(由$(this).attr('value, – bormat

2
  1. 您需要檢查jQuery的API文檔

$(document).ready(function(){});它需要函數回調,這可能不需要。

$("#foo").submit需要函數回調,它將在表單提交之前被調用。

無需在$.find

包裹選擇
  • 您需要弄清楚的this
  • $(this).attr("name")this上下文所指的輸入框

    this in $(this)[0].form仍然是輸入框

    我想你試圖得到forms的參考。你可以使用document.forms

    +0

    我已經對腳本進行了編輯,但仍然看不到預期的結果:https://jsfiddle.net/gvd1jr0o/1/ – cgrouge

    +0

    請讓我知道您的想法在更新後的腳本中,我仍然沒有在未勾選的複選框中獲得一個值 – cgrouge

    +0

    @cgrouge看看更新後的jsfiddle:https://jsfiddle.net/gvd1jr0o/6/ –

    相關問題