【问题标题】:Add Commas to checkbox array text Output将逗号添加到复选框数组文本输出
【发布时间】:2021-06-10 22:57:25
【问题描述】:

值之间需要 ","(逗号或换行符)
现在输出:ab
预期输出:a,b

我只是不确定它的确切位置。每次在开头或结尾我都会得到一个额外的逗号,例如“,a,c”或“a,c”。

$('.check').click(function() {
  $("#text").val('');
  $(".check").each(function() {
    if ($(this).prop('checked')) {
      $("#text").val($("#text").val() + $(this).val());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" class="check" id="a" value="a"><label for="a"> a</label><br>
<input type="checkbox" name="b" class="check" id="b" value="b"><label for="b"> b</label>
<br>
<input type="checkbox" name="c" class="check" id="c" value="c"><label for="c"> c</label><br>
<input type="text" name="text" id="text">

【问题讨论】:

  • 一种方法是将逗号与每个新值连接起来。另一种方法是构建一个值数组并用逗号join 它们。你尝试过什么,你在哪里卡住了?
  • 感谢输入。刚刚编辑了问题以清楚地了解它。

标签: jquery arrays text checkbox comma


【解决方案1】:

我建议选中所有复选框,filtering 仅选中复选框,mapping 值到数组,joining 数组使用逗号。

let $checks = $('.check');

$checks.on('click', function() {

  let values = $checks
    .filter(':checked')
    .map((k, box) => box.value)
    .toArray()
    .join(',');

  $("#text").val(values);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" class="check" id="a" value="a"><label for="a"> a</label><br>
<input type="checkbox" name="b" class="check" id="b" value="b"><label for="b"> b</label>
<br>
<input type="checkbox" name="c" class="check" id="c" value="c"><label for="c"> c</label><br>
<input type="text" name="text" id="text">

另见jQuery get values of checked checkboxes into array

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多