mardi 20 novembre 2018

Change input with string of multiple checkbox values

I need to be able to set the onclick function without onclick being in the input tag. The below code works great, but the input tags are generated and I cannot add the onclick event to them. Jquery solution is fine too.

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>



Aucun commentaire:

Enregistrer un commentaire