Reputation: 199
I have a JavaScript automated form creation formula. I'm struggling with the "selected" attribute of an option in a select list.
I'd like to have the option selected which matches the const c
(in this case, I'd like to have the option "Formation" selected).
How can I achieve this?
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);
Upvotes: 1
Views: 2480
Reputation: 112
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')
P.S. This works only if you're using native selects. Another option is to use fake selects though
Upvotes: 3
Reputation: 4415
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>';
}
Upvotes: 1