I have a HTML form along with a script, which automatically triggers the default "option" (option values hard-coded).
I also have a stand-alone script, which creates the choices of "options" dynamically, based on a specific column values in MySQL.
Problem: When selecting from the drop-down list from the dynamically generated list, it does not "trigger" anything (nor manual, nor automatic, manual would be just fine in this case)
The form which auto-triggers the default "option":
<form>
<select name="fruit" onchange="showFruit(this.value)">
<option>Choice:</option>
<option value="1">Yellow Fruit</option>
<option value="2">Red Fruit</option>
</select>
</form>
<script>
window.onload = function () {
var el = document.getElementsByName('fruit')[0];
el.value = 1;
el.onchange();
}
function showFruit(val) {
alert(val);
}
</script>
And the code which generates and displays the dynamically created list from a specific MySQL column:
<? $connect = mysqli_connect('localhost', '*', '*', '*');
$sql="SELECT DISTINCT(fruit_name) AS fruit_name FROM fruit ORDER BY fruit_name ASC";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$select= '<select name="select">';
while($rs = mysqli_fetch_array($result)){
$select.='<option value="'.$rs['id'].'">'.$rs['fruit_name'].'</option>';
}
}
$select.='</select>';
echo $select;
How can I have the onload function to attach to the dynamically generated "options" list? I don´t need any hard-coded "options" at all. Just the dynamically generated one. And when I select from the list, I would like to get a response/reaction of any sorts.
What I have tried:
I am trying to capture the selected option via the following, but can´t get it to work.
if ($result->num_rows > 0) {
$display = true;
$select = []
while ($row = $result->fetch_assoc()) {
$select[] = "<option value=\"{$row['id']}\">{$row['fruit_name']}</option>";
}
}