javascript jQuery:将复选框的值添加到输入文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22945014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:04:20  来源:igfitidea点击:

jQuery: Add values of checkboxes to input text field

javascriptjqueryhtmlcheckbox

提问by user1341808

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

我正在尝试将任何选中的复选框的值添加到输入文本字段。这是我的小提琴: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

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

在这个例子中,我有 3 个复选框,值为 1、2、3。如果我单击所有这些复选框,则输入字段应如下所示: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?

我该怎么做呢?

回答by George

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.

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

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.

map()返回一个包含选中复选框值的 jQuery 对象,get()将其转换为标准数组。用空格连接这些值并将它们放入输入中。

$(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

回答by pconnor88

On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:

单击复选框,遍历选中的输入,附加到一个字符串,然后将其分配给您的文本框:

$(document).ready(function() {
  $("input:checkbox").click(function() {
    var output = "";
    $("input:checked").each(function() {
      output += $(this).val() + " ";
    });
    $("#field_results").val(output.trim());
  });
});
<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

回答by epascarello

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) {

将始终为真,因为它返回一个 jQuery 对象并且一个对象是一个真值。如果要使用 if,则需要检查长度。又名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')

仅返回第一个元素的值并返回任何复选框,而不仅仅是选中的复选框。你想循环$(':checkbox:checked')

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

攻击它的一种方法是使用 each 和一个数组。

$(":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
});

回答by Satpal

Problem

问题

  1. if($(':checkbox:checked'))will always be true
  2. var fields = $(":checkbox").val();Will give first checkbox value
  1. if($(':checkbox:checked'))永远是真的
  2. var fields = $(":checkbox").val();将给出第一个复选框值

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