jquery get checkbox under div

Posted in :

我遇到一個checkbox 在 jsp 裡的問題,是使用者有勾,才會送出有勾選的值,如果有多個動態產生的block, 例如3筆資料,如果是使用 <input type=’text’ /> 不會有什麼問題,固定會送出3筆,但checkbox 很怪,如果只有勾在第 2個 block , 1 & 3 都沒勾,jsp 只會收到 checkbox 裡的值是什麼,無法得知是那一個block 裡的 checkbox 被勾選。

參考了下面這篇文章,就解決了:

文章 1號:


This is a derived ultimate solution that finds all checkboxes inside a DIV and checks or unchecks according to an other single checkbox outside the DIV which says check/uncheck

    function checkCheckboxes( id, pID ){

    $('#'+pID).find(':checkbox').each(function(){

        jQuery(this).attr('checked', $('#' + id).is(':checked'));

    });     

}

Usage:

<label>check/uncheck  
<input type="checkbox" id="checkall" value="1" 
onclick="checkCheckboxes(this.id, 'mycheckboxesdiv');" >
</label>

<div id="mycheckboxesdiv">
<input type="checkbox" value="test1" name="test">
<input type="checkbox" value="test2" name="anothertest">
<input type="checkbox" value="test3" name="tests[]">
<input type="checkbox" value="test1" name="tests[]">
</div>

Advantage is you can use independent checkbox sets and check / uncheck all independent from other sets. It is simple and no need to work with id or classes of each checkboxes.


 

文章 2號:


$(".test123 ").find("input:checked").each(function() {

Instead of the above one.. try using

    $("#button").click(function() {
        $(".test123").find("input:checkbox").each(function() {
            if($(this).attr('checked')) {
            } else {
                $(this).attr('checked','checked');
            }
        });
    });

 

文章 3號:


var selected = [];
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});

 

文章 4號:


In jQuery just use an attribute selector like

$('input[name="locationthemes"]:checked');

to select all checked inputs with name “locationthemes”

console.log($('input[name="locationthemes"]:checked').serialize());

//or

$('input[name="locationthemes"]:checked').each(function() {
   console.log(this.value);
});

Demo


In VanillaJS

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
   console.log(cb.value); 
});

Demo


 

我使用的 sample code, 原理是先把 checkbox 裡的值先放進去hidden ,然後頁面在顯示時,把 hidden 裡的值處理一下,再來顯示checkbox 就OK了。

 

jQuery(document).on('change','.isSupportedPlatform',function(){
  var allVals = [];
  jQuery(this).parent().parent().parent('div').find(':checked').each(function(){
      allVals.push($(this).val()); 
  });
  jQuery(this).parent().parent().parent('div').find('input:hidden').each(function(){
      $(this).val(allVals);
  });
});

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *