简体   繁体   中英

Dynamic checkbox list in javascript - not working

I'm trying to create a list of checkboxes when a certain element is selected from the dropdown list. However, in the following code I am getting only the last element in the checkbox list. That is, at the output, there aren't 3 checkboxes (length of my array) but there is only one - only with the last element in the array.

What am I doing wrong?

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>


    <script>
     function chooseTable(db) {


 if(db=="hr.employee"){

var div = document.getElementById("table"); 

var ids = ["id","name", "write_uid"];

var main = document.getElementById('main1');

var parentElement = document.getElementById('ids');

for(var count in ids)
{
    var newCheckBox = document.createElement('input');
    newCheckBox.type = 'checkbox';
    newCheckBox.id = 'id' + count; // need unique Ids!
    parentElement.innerHTML = ids[count];
    newCheckBox.value = ids[count];
    parentElement.appendChild(newCheckBox);

}

 }
 }


 </script>
  <center>
    <bold>
    <h2>
    Make Query
    </h2>
    </bold>

<div id="main1">
<div>

Choose database:<br/>

<select id="table" name="table" onchange="chooseTable(this.value)">

     <option name="choice" value=""></option>
    <option name="choice1" value="hr.employee">Employees</option>
    <option name="choice2" value="account.account">Accounts</option>
  </select>
</div>  

<div id="ids">

</div>
</div>

</center>

  </body>
</html>

because innerHTML method will clean its own inside and rewrite new element.
how about try this?

for(var count in ids)
            {
                var newCheckBox = document.createElement('input');
                var newSpan = document.createElement('span');
                newCheckBox.type = 'checkbox';
                newCheckBox.id = 'id' + count; // need unique Ids!
                newSpan.innerHTML = ids[count];
                newCheckBox.value = ids[count];
                parentElement.appendChild(newSpan);
                parentElement.appendChild(newCheckBox);

            }

the problem is the parentElement.innerHTML = ids[count]; code. It clean all the previous html content. And to add label to the checkbox it's better use label tag. Try this:

for(var count in ids)
{
    var newCheckBox = document.createElement('input');
    newCheckBox.type = 'checkbox';
    newCheckBox.id = 'id' + count; // need unique Ids!
    newCheckBox.value = ids[count];
    parentElement.appendChild(newCheckBox);
    var newLabel = document.createElement('label');
    newLabel.innerHTML = ids[count];
    parentElement.appendChild(newLabel);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM