简体   繁体   中英

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. The $r->category value contains some string that could be 'hot', 'new', etc.

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

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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