Mad Scientist
Mad Scientist

Reputation: 917

Dropdown menu always picks first option

I use a dropdown menu to choose options from a list which I get from a SQL query:

<div id="container" action="import.php" method="post" enctype="multipart/form-data">
<span id="pickfiles">[Upload files]</span>
</div>

echo ' <form action="import.php" method="post" id="pickfiles" enctype="multipart/form-data">
       Adresslieferant:  <select name="taskOption">
           <option value="" disabled selected hidden>Adresslieferanten auswählen</option>';

foreach ($sql as $row) {
echo "<option value=' ".  $row['firma'] . " ' name='adresslieferung' id='adresslieferung' type='text'>".  $row['firma'] ."</option>";
}
echo '  </select>
    </form> ';
?>

This is part of a form where I upload a csv file and this code snippet should choose one of the options of the dropdown menu which will be handed over in a javascript code snippet:

FileUploaded: function(up, files, info) {
  window.open('import.php?file='+files.name+'&address_delivery='+(document.getElementById('adresslieferung') && document.getElementById('adresslieferung').value ? document.getElementById('adresslieferung').value : ''), '_blank')
    },

But this way no matter which option I select at the dropdown menu. It always passes over the first choice of the dropdown menu. I guess it's because it just picks the first one with id='adresslieferung' but I don't know how else I could do it.

Upvotes: 3

Views: 845

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Problem is you are giving id to <options> instead of <select>, that's why when you try to get data using this id, it gives you the first value every-time.

Remove id from <options> and add it to <select>

    <div id="container" action="import.php" method="post" enctype="multipart/form-data">
        <span id="pickfiles">[Upload files]</span>
    </div>

    echo '<form action="import.php" method="post" id="pickfiles" enctype="multipart/form-data">
        Adresslieferant:
        <select name="taskOption" id='adresslieferung'><!-- added id here-->
            <option value="" disabled selected hidden>Adresslieferanten auswählen</option>';
            foreach ($sql as $row) {
            //Remove id from options
            echo "<option value=' ".  $row['firma'] . " ' name='adresslieferung' type='text'>".  $row['firma'] ."</option>";
            }
        echo '</select>
    </form>';
?>

Note:jQuery/javascript treated id as a unique attribute so make sure an id doesn't use twice in an HTML. You can use class concept in case you want to apply some event handling on a bunch of html elements.(give them same class and apply event handling in one go)

Upvotes: 2

Related Questions