dongzhuner6981 2015-02-06 11:03
浏览 144

PHP中select元素的默认值

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?

  • 写回答

1条回答 默认 最新

  • douchui4815 2015-02-06 11:21
    关注

    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>';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序