首页 > 解决方案 > 使用多个复选框值的字符串更改输入

问题描述

我需要能够在输入标签中没有 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>

标签: javascriptjquerycheckboxinputonclick

解决方案


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


推荐阅读