samedi 8 janvier 2022

Loop through document.getElementById in Typescript

I have the following array:

I have a list of check boxes and I would like to pre select them based on what I have in a array.

My checkboxes are:

Kiwi Banana Mango Apple Peach

<p>Choose your Fruit</p>

<br>

<div>
  <input type="checkbox" id="Apple" name="apple">
  <label for="apple">Apple</label>
</div>

<div>
  <input type="checkbox" id="Banana" name="banana">
  <label for="banana">Banana</label>
</div>

<div>
  <input type="checkbox" id="Kiwi" name="kiwi">
  <label for="kiwi">Kiwi</label>
</div>

<div>
  <input type="checkbox" id="Peach" name="peach">
  <label for="peach">Peach</label>
</div>

<div>
  <input type="checkbox" id="Mango" name="mango">
  <label for="mango">Mango</label>
</div>

Then in TypeScript I have an array with (and that can be changed): selectFruits = ['Kiwi', 'Apple'];

What I need is for those 2 fruits in the array to be checked in the html.

So far I tried this:

 selectFruits.forEach(function(i){
     var selectedFruit = document.getElementById(i) as HTMLInputElement
     selectedFruit.checked= true
    });

But that doesnt work because the selectedFruit returns null. Is there another way to achieve this or the document.getElementById shouldnt have been in the loop to start?




Aucun commentaire:

Enregistrer un commentaire