[英]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.