jQuery: Add values of checkboxes to input text field

后端 未结 4 693
梦如初夏
梦如初夏 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:53

    Problem

    1. if($(':checkbox:checked')) will always be true
    2. var fields = $(":checkbox").val(); Will give first checkbox value

    You can try this.

    $(document).ready(function() {
      $(":checkbox").on('click', function() {
        var fields = '';
        $(":checkbox").each(function() {
          if (this.checked) {
            fields += $(this).val() + ' ';
          }
        });
        $('#field_results').val($.trim(fields))
      });
    });
    
    
    
    1
    2
    3

提交回复
热议问题