1

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.