-1

i wanted to push the list of values selected from the checkbox to the text box that already has the array list of values......i mean when the data is been retrieved the textbox has its value (the retrieved value with the checkbox being checked)......when i select the new checkbox value and push that to the retrieved value.....the textbox only displays the newly selected checkbox values(the old checkbox values get removed)..........i want the textbox to display the old retrieved values with the currently selected checkbox values with checkbox being checked

var pc = [];

function getPc(myname1) {
 
 
 var text1 = myname1;
 
 
 if (document.getElementById(myname1).checked){
 
 
  pc.push(myname1);
     
 }
 else 
  {
     pc.splice( pc.indexOf(myname1), 1 );
  
  }
       console.log(pc);
 document.getElementById("pca").value = pc.join("/");
  
 
 
 }
<body onload="getpc()">
<p>Product Categories</p>
             <input type="text" class="form-control" id="pca" name="pc" form="form1" onclick="getPc()" value="myname1/check2/check3">
             
<input type="checkbox" name="myname1" id="myname1" onclick="getPc(this.id)"  checked>
<input type="checkbox" name="check2" id="check2" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check3" id="check3" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check4" id="check4" onclick="getPc(this.id)"  >
<input type="checkbox" name="check5" id="check5" onclick="getPc(this.id)" >
<input type="checkbox" name="check6" id="check6" onclick="getPc(this.id)" >
usr
  • 1
  • 5

1 Answers1

0

When the page loads check which checkboxes are checked and add them to the array.

var pc = [];

var checkboxes = document.getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].type == "checkbox") {
        if (checkboxes[i].checked) {
            getPc(checkboxes[i].id);
        }
    }
}

function getPc(myname1) {
    var text1 = myname1;
    if (document.getElementById(myname1).checked) {
        pc.push(myname1);
    } else {
        pc.splice(pc.indexOf(myname1), 1);
    }
    console.log(pc);
    document.getElementById("pca").value = pc.join("/");
}
<body>
<p>Product Categories</p>
             <input type="text" class="form-control" id="pca" name="pc" form="form1" onclick="getPc()" value="myname1/check2/check3">
             
<input type="checkbox" name="myname1" id="myname1" onclick="getPc(this.id)"  checked>
<input type="checkbox" name="check2" id="check2" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check3" id="check3" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check4" id="check4" onclick="getPc(this.id)"  >
<input type="checkbox" name="check5" id="check5" onclick="getPc(this.id)" >
<input type="checkbox" name="check6" id="check6" onclick="getPc(this.id)" >
Junius L
  • 15,881
  • 6
  • 52
  • 96