Click here to Skip to main content
15,921,989 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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; //Set default value
        el.onchange(); //trigger onchange event
    }

    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>";
    }
}
Posted
Updated 14-Oct-17 23:36pm
v2

1 solution

Your hard-coded version and the generated one are totally different...
HTML
<select name="fruit" onchange="showFruit(this.value)">
  <option value='...' >...</option>

HTML
<select name="select">
  <option value='...' >...</option>

Your hard-coded code knows only about 'fruit' and not 'select' (which can be all right depends on your design), but what is for sure wrong is that there is no even handler attached to 'select'...
Update your code like this:
PHP
$select= '<select name="select" onchange="showFruit(this.value)">';
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900