jQuery: Add values of checkboxes to input text field

后端 未结 4 738
梦如初夏
梦如初夏 2021-01-16 13:17

I\'m trying to add the values of any checked checkbox to an input text field. Here\'s my fiddle: http://jsfiddle.net/Lf6ky/

4条回答
  •  一个人的身影
    2021-01-16 13:49

    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.

    $(document).ready(function(){
        $checks = $(":checkbox");
        $checks.on('change', function() {
            var string = $checks.filter(":checked").map(function(i,v){
                return this.value;
            }).get().join(" ");
            $('#field_results').val(string);
        });
    });
    
    
    1
    2
    3

提交回复
热议问题