1

I am attaching my html code to a variable(ctableData) which I am again appending to the main container. Now I want to have dynamic id for the checkbox, So I am running a loop and incrementing the value of k in every iteration and then assigning the k as checkbox id. But this doesnt seem to be working?

for(let k =1; k< x.length; k++){
ctableData += '<div class="table_container"><table id="table1" class="checkboxdiv"><tbody><tr><th>'+plan[0].medicalPlans[i].brokerName+' <input type="checkbox" id= k name="table1" value="table1" onchange="myFunction(event)"> </th></tr>
}
sd_30
  • 576
  • 1
  • 6
  • 21

3 Answers3

2

Use a template string using backticks.

for(let k =1; k< x.length; k++){
ctableData += `<div class="table_container">
    <table id="table1" class="checkboxdiv">
      <tbody>
        <tr>
          <th>'+plan[0].medicalPlans[i].brokerName+' 
            <input type="checkbox" id=${k} name="table1" value="table1" onchange="myFunction(event)" /> 
          </th>
        </tr>
      </tbody>
      </table>
    </div>`
}
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
1

The issue with your code is that you haven't used the value of k. You put k inside the string which does not evaluate to a loop variable. Use it just like you did for plan[0].medicalPlans[i].brokerName :

 for (let k = 1; k < x.length; k++) {
  ctableData += '<div class="table_container">
                   <table id="table1" class="checkboxdiv"><tbody><tr><th>' 
                  + plan[0].medicalPlans[i].brokerName + ' 
                    <input type="checkbox" id=' + k + ' name="table1" 
                   value="table1" onchange="myFunction(event)"> </th></tr>
     }
K K
  • 17,794
  • 4
  • 30
  • 39
1

Try using template literals.

for(let k =1; k< x.length; k++){
ctableData += 
`<div class="table_container">
     <table id="table1" class="checkboxdiv">
         <tbody>
             <tr>
                 <th>'+plan[0].medicalPlans[i].brokerName+'
                    <input type="checkbox" id=${k} name="table1" value="table1" 
                    onchange="myFunction(event)"> 
                 </th>
             </tr>
         <tbody>
     <table>
</div>`
}
M.Hassan Nasir
  • 851
  • 2
  • 13