我需要能够设置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>
答案 0 :(得分:0)
//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>
答案 1 :(得分:0)
使用SendMessage
函数
.map()
$(".checkbox").change(function() {
$("#text").val( $('.checkbox:checked').map(function() { return this.value; }).get().join(','));
});
答案 2 :(得分:-1)
您可以尝试以下方法:
IAM
答案 3 :(得分:-1)
普通JS:
var mForm = document.getElementById("form1");
mForm.addEventListener("click", function(event){
console.log("clicked", event.toElement); // do whatever you want with this element, add condition to sort checkboxes only
});
已更新:
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
function setValue(frm, cbs){
var output = [];
for( var n in cbs){
if(cbs[n].checked){
output.push(cbs[n].value);
}
}
frm.textname.value=output.join();
}
frm.addEventListener("click", function(event){
if (event.toElement.type == "checkbox") {
setValue(frm, cbs);
}
});