2011-09-14 95 views
0

在我的網站上,我有一張門票列表。在該列表的頂部,我有這個複選框,可以檢查所有複選框,在列表中:添加值輸入 - jQuery

<input type="checkbox" id="checkall" class="checkall" name="checkall"> 

該複選框,檢查所有其他複選框有以下的jQuery:

$(document).ready(function(){ 
    $('#checkall').toggle(function(){ 
     $('input:checkbox').attr('checked','checked'); 
     $(this).val('uncheck all') 
    },function(){ 
     $('input:checkbox').removeAttr('checked'); 
     $(this).val('check all');   
    }) 
}) 


$('input:checkbox').click(function() { 
    $("#userInfo").toggle(!($('input:checkbox:checked').length == 0)); 
}); 

$('#close').click(function() { 
    $("#userInfo").hide(); 
    $('input:checkbox').removeAttr('checked'); 
}); 

雖然,我也希望將所有選中的複選框值放入我的表單中。我使用此代碼爲:

function updateTextArea() 
    { 
     var allVals = []; 
     $('#c_b :checked').each(function(){ 
      allVals.push($(this).val()); 
     }); 
     jQuery('#ticketIds').val(allVals); 
    } 
    $(function() 
    { 
      $('#c_b input').click(updateTextArea); 
      updateTextArea(); 
    }); 

這裏是我的表格:

<form method="post" name="edit"> 
    <input type="hidden" id="ticketIds" name="ticketIds" value="">  
    <input type="submit" class="button gray" value="Okay, do it" name=""> <a href="#" id="close">Close</a></form> 

我的問題是,每當我用「檢查所有」複選框,沒有值被添加到#ticketIds。只有當我自己檢查每個複選框時,值纔會被添加。

我該怎麼辦,所以這兩種方式?

+0

據透露,你可以使用'.prop('checked',val)'','val'是一個布爾值。 – ThiefMaster

回答

1

嘗試調用你的函數,只要你點擊選擇/取消所有複選框:

$(document).ready(function(){ 
    $('#checkall').toggle(function(){ 
     $('input:checkbox').attr('checked','checked'); 
     $(this).val('uncheck all') 
     updateTextArea(); 
    },function(){ 
     $('input:checkbox').removeAttr('checked'); 
     $(this).val('check all'); 
     updateTextArea();  
    }) 
}) 
+0

謝謝!奇蹟般有效 –

-1

不知道我理解你想什麼來完成,但是這可能幫助:

$('#checkall').toggle(function(){ 
    $('input:checkbox').attr('checked','checked'); 
    $('input:checkbox').trigger('click'); // add this line 
    $(this).val('uncheck all') 
},function(){ 
//... 
+0

非常不好......爲頁面上的每個複選框調用'updateTextArea()'一次。它只需要調用一次。 –