I think this is a cleaner approach to what has been offered so far...
var values = [];
$('#chicken, #meat').filter(':checked').each(function() {
values.push($(this).attr('id'));
});
$('#hidden_field').val(values.join(','));
Instead of updating the hidden field when a user checks one of the boxes, you should run the above code in the form's submit event, so it only has to do it once when the form is finally being sent:
$('#myform').submit(function() {
// update the hidden field...
var values = [];
$('#chicken, #meat').filter(':checked').each(function() {
values.push($(this).attr('id'));
});
$('#hidden_field').val(values.join(','));
// and submit the form
return true;
});
Also, as it is right now the only place where I could easily tell the value you want is coming from is the id
attribute of the checkboxes. The solutions that are using val()
that were posted would return blank because you have no value=""
attribute in your checkboxes. If you wanted to update the hidden field with the value=""
attribute (which is the expected behavior) you should add the attribute in and then change $(this).attr('id')
to $(this).val()
in the code above.
EDIT (in response to comment):
If you have more than the 2 checkboxes that you show, you need to change the selector. Above I used $('#chicken, #meat')
. If you wanted to include all the checkboxes in the document, you would change it to $('input:checkbox')
, but probably the best way (to avoid unexpected behavior later on) is to give all the checkboxes you want to include in the hidden field a common class and then make your selector something like $('input.myclass:checkbox')
. Finally, as long as you match your form's ID to ID I used above (myform
) then the updating of the hidden field should be taken care of for you automatically when the form is submitted (assuming also the hidden field has an id of hidden_field
and the user has Javascript enabled...). Also, you need to make sure the form binding code above is wrapped around $(document).ready(function() { // code here });
otherwise the code will run before the DOM is ready and you will be binding the event to a non-existent element.