How to select a select box element using java script when select box using foreach in php

i have select box element using foreach in php :

    <select class="form-control" id="sopir" name="sopir">
          <?php
            foreach($array_sopir as $nik=>$nama){
                echo '<option value="'.$nik.'">'.$nama.'</option>';
            }
          ?>
   </select>

I have tried to use this document.getElementById('sopir').value = valueToSelect; but it does not work. how can i to select value with javascript ?

1 answer

  • answered 2018-07-11 03:50 Pupil

    Change:

    document.getElementById(sopir).value = valueToSelect;

    To

    document.getElementById('sopir').value = valueToSelect;

    Missing single/double quotes around the sopir indicates that sopir is a variable and not actual element id.

    Provided valueToSelect has a value that matches at least one option from drop down.