javascript - 在复选框的输入文本中一一追加

标签 javascript jquery checkbox

我有一个 jQuery将所有复选框值附加到一个 <input type="text"/> 中的脚本与 ',' ,但是当我选中一个复选框时,它也会附加其他复选框中的所有值,而我只想附加我按顺序选中的值。

$('.check_list').on('change', function() {
  var n = $(this).siblings('input:checkbox');
  var nControl = $('.codeParc');

  if ($(this).prop('checked')) {
    n.prop('checked', true);
    var vals = nControl.map(function() {
      return $(this).val();
    }).get().join(',');

  } else {
    n.prop('checked', false);
  }
  $('#test').val(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list"></input>
<input type="checkbox" class="codeParc" value="1"></input>
<input type="checkbox" class="codeParc" value="2"></input>
<input type="checkbox" class="codeParc" value="3"></input>

<input type="text" id="test" value=""></input>

此代码返回所有值 1,2,3每当我选中一个复选框时,我需要的是选中一个复选框并仅显示他的号码,然后在选中时附加其余部分。

最佳答案

首先注意input元素是自闭合的,所以它是 <input /> , 不是 <input></input> .

一个更简单的方法是将选定的值映射到一个数组中并更新 input 的文本每次单击复选框时都会使用该数组中的值,如下所示:

$('.check_list').change(function() {
  $('.codeParc').prop('checked', this.checked);
  updateText();
});

$('.codeParc').change(function() {
  $('.check_list').prop('checked', $('.codeParc').length == $('.codeParc:checked').length);
  updateText();
});

function updateText() {
  var checkedValues = $('.codeParc:checked').map(function() {
    return this.value;
  }).get();
  $('#test').val(checkedValues.join(','));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list" />
<input type="checkbox" class="codeParc" value="1" />
<input type="checkbox" class="codeParc" value="2" />
<input type="checkbox" class="codeParc" value="3" />
<input type="text" id="test" value="" />

关于javascript - 在复选框的输入文本中一一追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896810/

相关文章:

javascript - 输入类型文本 - 如何根据其在网页中的位置在下方或上方添加 div

javascript - jQueryMobile - 滚动到一个位置 onLoad

javascript - 页面导航到 localhost :3000/? 在输入框中输入按下

javascript - 如何使用 jQuery 或 JavaScript 过滤掉超出范围的结果

javascript - 无法使用状态内的数组初始化 React 复选框

javascript - 使用 map 功能时如何动态地将每个状态绑定(bind)到每个复选框

javascript - 如何防止页面在表单提交后重新加载 - JQuery

javascript - 单击导航

javascript - 这个指数分布采样器在密码学上是安全的吗?

javascript - chrome 中的复选框很小且不可点击