首页 > 解决方案 > 在文本框中显示复选框值

问题描述

我要实现的是,我有一个复选框,其中一个值=“”选中复选框时,值应在文本框中显示。

<input type="text" id="results">
<div id="multiselect-drop">
<input type="checkbox" value="Testing the textbox">
<input type="checkbox" value="Testing 2 the textbox">
</div>
<script>
$('#multiselect-drop input').change(function() {
  if (this.checked) {
    $li = $('<li></li>');
    $li.text(this.value);
    $('#results').append($li);
  }
  else {
    $('li:contains('+this.value+')', '#results').remove();
  }
});
</script>

编辑:如果我有多个复选框怎么办?我可以在用逗号分隔的文本框中显示所有选中的项目吗?

标签: jquerydropdown

解决方案


li您不应该将元素附加到input

试试这个代码:

$('#multiselect-drop input').change(function() {
  if (this.checked) {
    $('#results').val(this.value);
  } else {
    $('#results').val("");
  }
});

如果需要,您还可以移动if语句:

$('#multiselect-drop input').change(function() {
  $('#results').val((this.checked ? this.value : ""));
});

演示

$('#multiselect-drop input').change(function() {
  var s = $('#multiselect-drop input:checked').map(function() {
    return this.value;
  }).get().join(',');
  $('#results').val((s.length > 0 ? s : ""));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="results">
<div id="multiselect-drop">
  <input type="checkbox" value="Testing the textbox">
  <input type="checkbox" value="another textbox">
</div>


推荐阅读