简体   繁体   中英

Default value for select element from PHP

I have created a contacts database using PHP, MySQL on a XAMPP server. The page opens with a 'Contacts' table with Add, Edit & Delete buttons. Add & Delete are working fine. Edit button opens a modal form with all the usual inputs which are filled in with values from the table row using...

$("#dlgeditContactName").val(ContactName);
$("#dlgeditEmail").val(Email);

etc.

There is also a select element (Contact Type) which is populated using PHP...

<?php

$conn  =   new mysqli('xxxx', 'xxxx', 'xxxx', 'xxxx')  or die ('Cannot connect to db');

    $result  =   $conn->query("select contacttypeid, contacttype from tblcontacttypes");

    echo "<select id =  'dlgeditcontacttypeid'>";

    while ($row  =   $result->fetch_assoc()) {
        unset($id, $name);
        $id  =   $row['contacttypeid'];
        $name  =   $row['contacttype']; 
        echo '<option value =  "'.$id.'">'.$name.'</option>';
    }
    echo "</select>";

?>

The contacttypeid & contacttype are int and string eg. 1, Personal 2, Family etc.

At the moment this select box acts as expected and user can choose an option during an edit session.

I just don't know the best way to put a default value in this select box based upon what's in the value in the table row. Filling the other input elements was easy but using the following for the select does not work...

$("#dlgeditcontacttypeid").val(ContactTypeID);

I think I will have to use 'selected' as in ...

<option value="audi" selected>Audi</option>

(from W3Schools), but not sure if this is best or even how to do it.

I thought of a hidden div on the form with the ID but no luck getting the value to PHP

I tried putting some Java inside the PHP ...

echo "<script> function(); </script>";

but it looks 'messy' and I don't believe it's the best approach

There must be a standard method for this issue - anyone had to deal with this?

Is this what you are looking for:

$ContactTypeID = 2; //Considering you have default value with you.

while ($row  =   $result->fetch_assoc()) {
    unset($id, $name);
    $id  =   $row['contacttypeid'];
    $name  =   $row['contacttype'];

    if($id == $ContactTypeID) //If default value and id in loop are same
    echo '<option value =  "'.$id.'" selected="selected">'.$name.'</option>';
    else
    echo '<option value =  "'.$id.'">'.$name.'</option>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM