简体   繁体   English

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

[英]Set select element option on page load

I want the page to auto-select some value ('hot', 'new', etc.) depending on the $r->category value which is loaded from database. 我希望页面根据从数据库加载的$r->category值自动选择一些值(“ hot”,“ new”等)。 The $r->category value contains some string that could be 'hot', 'new', etc. $r->category值包含一些可能是'hot','new'等的字符串。

Input element: 输入元素:

<input type="text" id="cex" value="<?php echo $r->category?>">

The select option: 选择选项:

<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>

The javascript function 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;             
}

Currently, your code will set the value of the select element to the initial value every time any option is selected. 当前,每次选择任何选项时,您的代码都会将select元素的值设置为初始值。 For example, if 'hot' is the value from the server, and a user selects 'new' , the cek function will execute in the change event and change the value back to 'hot' . 例如,如果'hot'是服务器中的值,并且用户选择'new' ,则cek函数将在change事件中执行,并将值更改回'hot'

Instead, only set the select element's value to the initial value from the server once. 相反,仅将一次选择元素的值设置为来自服务器的初始值。 A working example is below. 下面是一个工作示例。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM