Search code examples
phpdatabasedrop-down-menuselectedindex

Change the selectedIndex in a combo box according to data loaded from a database (PHP)


I have a database of Employees and a dropdown list which I generated with PHP, then with javascript I tried to put the right type of blood of each employee in the database.

I have a database of Employees and a dropdown list which I generated with PHP, then with javascript I try to put the right type of blood for each employee in the database.

First I retrieved the data:

$rsEmployee = employee::getEmployees();
        while($row = mysql_fetch_assoc($rsEmployee))
        {
    echo "
    <select id='slcBloodType' name='slcBloodType' onload='chooseItem(this, '$row['slcBloodType']')'>
    <option value='A+'> A+ </option>
    <option value='A-'> A- </option>
    <option value='B+'> B+ </option>
    <option value='B-'> B- </option>
    <option value='AB+'> AB+ </option>
    <option value='AB-'> AB- </option>
    <option value='O+'> O+ </option>
    <option value='O-'> O- </option>
    </select>";
}

The javascript function:

function elegirOption(list, value){
                array = ["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"];

                index = -1;
                for(var i = 0; i < array.length; i++){
                    if(value == array[i]){
                        index = i;
                        break;
                    }
                }
                if(index != -1){
                               this.selectedIndex = index;
                            }
            }

But is not working, it seems that I can't pass a php variable as a parameter to a javascript function...

There are others dropdown list with which I want to do that.


Solution

  • Why not do it like this:

    $blood_types = array("A+", "A-", ...);
    echo '<select>';
    
    while(....) {
    
      foreach($blood_types as $blood_type) {
        echo '<option';
        if($blood_type == $row['slcBloodType'])
           echo 'selected="selected"';
        echo '>'.$blood_type.'</option>';
      }
    }
    

    You don't have to specify the value attribute since it's the same as the text.