jQuery:在输入文本字段中添加复选框的值

问题描述:

我正在尝试将任何选中复选框的值添加到输入文本字段中。
这是我的小提琴: http://jsfiddle.net/Lf6ky/

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

$(document).ready(function() {
  $(":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 + " ");
      });
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<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

在这个例子中,我有3个复选框,值1,2,3。如果我点击所有这些复选框,那么输入字段应如下所示:1 2 3

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.

我该怎么做?

我已将复选框的集合存储在变量 $ checks 中,然后将处理程序附加到此集合。在事件处理程序中,我再次获取集合并过滤(返回)仅检查的复选框。

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()返回一个包含已检查复选框值的jQuery对象, get()将其转换为标准数组。用空格加入这些值并将'em'放在输入中。

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);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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