[英]Set select element option on page load
我希望頁面根據從數據庫加載的$r->category
值自動選擇一些值(“ hot”,“ new”等)。 $r->category
值包含一些可能是'hot','new'等的字符串。
輸入元素:
<input type="text" id="cex" value="<?php echo $r->category?>">
選擇選項:
<select name="ktgr" onChange="cek();">
<option id='n' value="normal">normal</option>
<option id='h' value="hot">hot</option>
<option id='nw' value="new">new</option>
<option id='u' value="upcoming">upcoming</option>
</select>
javascript功能
function cek()
{
var j = document.getElementById("cex").value;
if(j=='normal')
document.getElementById('n').selected=true;
else if(j=='hot')
document.getElementById('h').selected=true;
else if(j=='new')
document.getElementById('nw').selected=true;
else if(j=='upcomming')
document.getElementById('u').selected=true;
}
當前,每次選擇任何選項時,您的代碼都會將select元素的值設置為初始值。 例如,如果'hot'
是服務器中的值,並且用戶選擇'new'
,則cek
函數將在change事件中執行,並將值更改回'hot'
。
相反,僅將一次選擇元素的值設置為來自服務器的初始值。 下面是一個工作示例。
function cek() { var j = document.getElementById("cex").value; if (j == 'normal') document.getElementById('n').selected = true; else if (j == 'hot') document.getElementById('h').selected = true; else if (j == 'new') document.getElementById('nw').selected = true; else if (j == 'upcoming') document.getElementById('u').selected = true; }
<body onload="cek()"> <input id="cex" value="new" /> <select name="ktgr"> <option id='n' value="normal">normal</option> <option id='h' value="hot">hot</option> <option id='nw' value="new">new</option> <option id='u' value="upcoming">upcoming</option> </select> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.