台灣最大程式設計社群網站
線上人數
810
 
會員總數:245973
討論主題:189551
歡迎您免費加入會員
討論區列表 >> PHP >> (轉載) 設計下拉式選單
[]  
[我要回覆]
回應主題 加入我的關注話題 檢舉此篇討論 將提問者加入個人黑名單
(轉載) 設計下拉式選單
價值 : 10 QP  點閱數:1556 回應數:0
樓主

豆豆
初學者
476 175
1382 595
發送站內信

共有2個例子,第1個例子係使用陣列。第2個例子係結合資料表,該例只用了2個欄位,可視用途擴充欄位個數,這例子只適用於欄位值無關聯性或遞迴關係的應用。

作者:Olaf Lederer

第1例:使用陣列
<?php
// build here the array with values for the select,
// notice that the array key is used option value and the array value as the label.
$test_array = array("var_1"=>"first label", "some_var"=>"it's hot", "last_constant"=>"last element");

// the properties of this function the array above, the name of the select menu and the initial value.
// If the initial value is empty (by default the an empty option is added otherwise.
// Use only a valid key from the above array as initial value and the selected state is used for this value.
function dynamic_select($the_array, $element_name, $init_value = "") {
$menu = "<select name=\"".$element_name."\">\n";
if (!isset($_REQUEST[$element_name])) {
if ($init_value == "") {
$menu .= " <option value=\"\">...\n";
} else {
$curr_val = $init_value;
}
} else {
$curr_val = $_REQUEST[$element_name];
}
foreach ($the_array as $key => $value) {
$menu .= " <option value=\"".$key."\"";
$menu .= ($key == $curr_val) ? " selected" : "";
$menu .= ">".$value."\n";
}
$menu .= "</select>\n";
return $menu;
}
echo dynamic_select($test_array, "test_menu", "some_var");

//will output this:
//<select name="test_menu">
// <option value="var_1">first label
// <option value="some_var" selected>it's hot
// <option value="last_constant">last element
//</select>
//
?>

第2例:結合資料表的欄位值

col_for_value、col_for_label為資料表的欄位,some_table是資料表名稱。

<?php
// example sql statement
$sql = "SELECT col_for_value, col_for_label FROM some_table";

function database_select($tbl_value, $tbl_label, $select_name, $label) {
global $sql;
$result = mysql_query($sql);
$menu = "<label for=\"".$select_name."\">".$label."</label>\n";
$menu .= "<select name=\"".$select_name."\">\n";
$menu .= " <option value=\"\"";
$menu .= (!isset($_REQUEST[$select_name])) ? " selected" : "";
$menu .= ">...\n";
while ($obj = mysql_fetch_object($result)) {
$menu .= " <option value=\"".$obj->$tbl_value."\"";
$menu .= (isset($_REQUEST[$select_name]) && $obj->$tbl_value == $_REQUEST[$select_name]) ? " selected" : "";
$menu .= ">".$obj->$tbl_label."\n";
}
$menu .= "</select>\n";
mysql_free_result($result);
return $menu;
}

// example:
// use the col names from the table too...
echo database_select("col_for_value", "col_for_label", "my_select", "Select from:");

/* example output

<label for="my_select">Select from:</label>
<select name="my_select">
<option value="" selected>...
<option value="val_1">value 1
<option value="val_2">value 2
...
</select>

*/
?>

本篇文章發表於2005-04-01 20:32
目前尚無任何回覆
   

回覆
如要回應,請先登入.