jquery - 在文本框中显示复选框值
问题描述
我要实现的是,我有一个复选框,其中一个值=“”选中复选框时,值应在文本框中显示。
<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>
编辑:如果我有多个复选框怎么办?我可以在用逗号分隔的文本框中显示所有选中的项目吗?
解决方案
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>
推荐阅读
- mysql - 如何从表中提取信息以填充已创建数据仓库中的 CALENDAR 表
- google-apps-script - 如何在编辑上触发谷歌电子表格功能?
- html - 一些 CSS 样式表没有加载
- django - 访问 OneToOne 关系并传递给 django 中的模板
- javascript - webpack 4.7.x 还需要 babel-loader 吗?
- tsql - 为什么我们需要表值参数
- android-gradle-plugin - gradle android - 谷歌服务 3.2.0 [错误] [com.android.build.gradle.internal.transforms.DesugarTransform]
- r - mutate_all 后的 dplyr::summarise_all 错误
- angular - PubNub Angular2 AddListener - 调用函数
- sql-server - 使用 T-SQL CTE 进行递归选择