Search code examples
javascripthtmlangularjsdropdown

In AngularJS or html or Javascript, need to add <td> cells to a table based on dropdown selection


I have a dropdown box:

 <select ng-model="numberselected">    
   <option value="">Select One</option>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
 </select>

I have a table:

 <table>
   <tr>
     <td>row </td>
     <td><input></input></td> 
   </tr>                   
 </table> 

I need as many

 <td><input></input></td>

as the user selected in the dropdown. How can I do this in AngularJs? Or html? or javascript?


Solution

  • You could use the insertCell, for doing this you have to get the row in wich you want to add the td

    const SelectedVal = (e)=>{
        let element = document.getElementById('row')
        let i = parseInt(e.value)
      let numberTd = [...element.childNodes].filter(el=>{return el.tagName == 'TD'}).length
      
      for(let z = 0;z<numberTd;z++){
         element.deleteCell(0)
      }
      
      for(let x = 0;x<i;x++){
      var tdAdded = element.insertCell(0);
      tdAdded.innerHTML = "New cell";
      }
    }
     <table>
       <tr id="row">
         <td>row </td>
       </tr>                   
     </table> 
     
      <select onchange="SelectedVal(this)" >    
       <option value="">Select One</option>
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>
     </select>