javascript - 使用多个复选框值的字符串更改输入
问题描述
我需要能够在输入标签中没有 onclick 的情况下设置 onclick 功能。下面的代码效果很好,但是会生成输入标签,我无法向它们添加 onclick 事件。Jquery 解决方案也很好。
function setValue(){
var val="";
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
for(var n=0;n<cbs.length;n++){
if(cbs[n].checked){
val+=cbs[n].value+",";
}
}
var temp = val.split(",");
temp.pop();
frm.textname.value=temp
}
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="tea" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="beer" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="soda" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="orangejuice" onclick="setValue(this.value);">
<input type="text" name="textname">
</form>
解决方案
//attach a change handler to the form.
//the change event bubbles up to the parent
var $form = $('#form1').on('change', function(){
//set the value of the textname
$form.find('[name="textname"]').val(
//get all the checked checkbox and map all their values to an array
$form.find(':checkbox:checked').map(function(){
//return the value for each checked element
return this.value;
}).get() //use get() to get a basic array, not a jQuery object
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee">
<input type="checkbox" name="amenities[]" value="tea">
<input type="checkbox" name="amenities[]" value="beer">
<input type="checkbox" name="amenities[]" value="soda">
<input type="checkbox" name="amenities[]" value="orangejuice">
<input type="text" name="textname">
</form>
推荐阅读
- c# - 使用 U-SQL 从文本文件中删除特殊字符
- jenkins - 从 Jenkins 管道获取 ssh-steps 输出
- python - 数据集的二值化会导致重复。有什么解决方案吗?
- swift - 如何在组合中实现正确的 switchMap 运算符?
- javascript - JavaScript 中的对象字面量和类有什么区别?
- java - 不从@Mapper 接口调用@AfterMapping
- laravel - 如何同时以另一个用户身份登录
- arrays - 在未排序数组中搜索的有效方法
- reactjs - react-dropzone 图像在上传时旋转
- python - 处理python和oracle之间异常握手的正确方法