【问题标题】:Show check box value in a textbox在文本框中显示复选框值
【发布时间】:2020-10-09 13:07:47
【问题描述】:

我正在尝试实现的是,我有一个复选框,值=“”当检查复选框时,值应该在文本框中显示。

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

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

【问题讨论】:

  • 为什么不干脆做$('#results').val(this.value); 呢?为什么要将 li 附加到文本框?

标签: jquery dropdown


【解决方案1】:

您不应将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>

【讨论】:

  • 这确实很有帮助,但是如果有多个具有不同值的复选框怎么办?如何在逗号分隔的文本框中显示所有值?
【解决方案2】:

你可以用这个

$("#multiselect-drop input").change(
 function(){
  if($(this).is(':checked')){
    $("#results").val($(this).val());
  }
  else {
    $("#results").val("");
  }
 }
);
<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">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2013-11-25
    相关资源
    最近更新 更多