jQuery: Add values of checkboxes to input text field

后端 未结 4 736
梦如初夏
梦如初夏 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 14:11

    First issue is

    if($(':checkbox:checked')) {
    

    will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {

    Secondly

    var fields = $(":checkbox").val();
    

    returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')

    One way to attack it is to use an each and an array.

    $(":checkbox").on('change', function() {
        var total = [];
        $(':checkbox:checked').each( function(){  //find the checked checkboxes and loop through them
            total.push(this.value); //add the values to the array
        });        
        $('#field_results').val(total.join(" "));  //join the array
    });
    

提交回复
热议问题