简体   繁体   中英

How to add “selected” attribute dynamically to select option in javascript?

I have a javascript automated form creation formula. I'm struggling with the "selected" attribute of option in a select list. I'd like to have the option selected which matches the the const c (in this case, i'd like to have the option "Formation" selected).

How can I achieve this ? Any idea ? thanks a lot from France !

const c = "Formation";                

const training_level = document.createElement('select');
training_level.setAttribute('value', c)
training_level.setAttribute('id', 'rec_mode')
training_level.required = true

var j = new Array("-- Type de diplôme --","Formation","Brevet","Bac","Bac +1"),    
var options = '';

for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i]+ '">' + j[i] + '</option>';
}

training_level.appendChild(options);

Test if the value of c matches the value of j[i] . Use the value of that condition to fill in the selected attribute:

for (var i = 0; i < j.length; i++) {
    var selected = (c == j[i]) ? "selected" : "";
    options += '<option value="' + j[i]+ '" selected="' + selected + '">' + j[i] + '</option>';
}

Suppose you have an option with id opt1 like

<option value="your_value" id="opt1">option text</option>

then you can do

document.getElementById('opt1').setAttribute('selected', 'selected')

PS This works only if you're using native selects. Another option is to use fake selects though

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