简体   繁体   中英

Get the values of all checked check boxes and put them in a hidden field

How do I modify this simple check all code to get all the values of the checkboxes after they are checked and then place them into hidden input, each value should be separated with a comma so I can then explode the values in php. The checkboxes are inside table rows

//checks all and unchecks all checkboxes based on checkbox in first row of the table.
 $('th input:checkbox').click(function(e) {
    var table = $(e.target).parents('table:first');
    $('td input:checkbox', table).attr('checked', e.target.checked);

 });

You can do it like this:

$('th input:checkbox').click(function(e) {

   var currentChecked = $('#hiddenInput').val(); 

   if($(this).is(':checked'){
        $('#hiddenInput').val(currentChecked  + ',' + $(this).val());
   }

   //deleting the unchecked checkbox from the list
   else{
       var newValue = currentChecked .replace("," + $(this).val(), "");
   }

});

Living example: http://jsfiddle.net/mR85S/

you can try this like at this post jQuery to populate hidden input but retain existing content :

 function Populate(){ vals = $('input[type="checkbox"]:checked').map(function() { return this.value; }).get().join(','); console.log(vals); $('#tags').val(vals); } $('input[type="checkbox"]').on('change', function() { Populate() }).change(); 

and the jsFiddle

I'll assume your code already works to check all those checkbox. Basically, you only want to get the values of every checkbox you checked.

//checks all and unchecks all checkboxes based on checkbox in first row of the table.
 $('th input:checkbox').click(function(e) {
    var table = $(e.target).parents('table:first');
    var checkboxes = $('td input:checkbox', table).attr('checked', e.target.checked);
    var values = '';
    if(e.target.checked) {
       for(var i=0; i<checkboxes.length; i++) {
          values += $(checkboxes[i]).val() + ','; // the val method cant retrieve all the values of a set
       }
       values = values.substr(0, values.length - 1);
    }

    //place values in your hidden input

 });

That should do the trick.

Does this help?

$('th input:checkbox').click(function (e) {
    var table = $(e.target).parents('table:first');
    var vals = [];
    $('td input:checkbox', table).each(function(){
        $(this).attr('checked', e.target.checked);
        vals.push($(this).attr('checked') ? $(this).val() : '');
    });
    $('#hidden').val(vals.join());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM