user1341808 user1341808 - 6 months ago 33
jQuery Question

jQuery: Add values of checkboxes to input text field

I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle:

<input type="text" id="field_results"/><br>

<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3

$(":checkbox").on('click', function() {
if($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each( fields, function( i, field ) {
$('#field_results').val($('#field_results').val() + field.value + " ");

In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3

If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.

How do I do this?


I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.

map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.

    $checks = $(":checkbox");
    $checks.on('change', function() {
        var string = $checks.filter(":checked").map(function(i,v){
            return this.value;
        }).get().join(" ");