简体   繁体   中英

How I set the a field in a input select (HTML) with javascript?

I will randomly select a number and define the selected field in a select with the sorted number. How I set the field?

Add the Attribute selected="selected" to the option element that you want to select.

pseudo code

function foo()
{
create list of option elements
generate random number
get a single option element at index of random number
set all options attribute "selected" = null
set the option element[at index of random number] attribute selected = "selected"
}
var randomNumber = 3; // just for example 
document.getElementById('select_field').selectedIndex = randomNumber;

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