在页面加载时设置select元素选项

Set select element option on page load

本文关键字:select 元素 选项 设置 加载      更新时间:2023-09-26

我希望页面根据从数据库加载的$r->category值。$r->category值包含一些可能是"热"、"新"等的字符串。

输入元素:

<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函数将在更改事件中执行,并将值更改回'hot'

相反,只从服务器将select元素的值设置为初始值一次。下面是一个工作示例。

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>