I am programmatically creating a select
-element with a few options. I want to make a specific option selected. For this I use option.selected = true
. I also tried option.selected = 'selected'
.
This is my code:
let select_menu_for_sequence = document.createElement("select");
select_menu_for_sequence.classList.add("sequence");
for (i = 1; i <= 4; i ) {
let option = document.createElement("option");
option.text = i;
if (i == 2) {
option.selected = true;
}
select_menu_for_sequence.appendChild(option);
}
console.log(select_menu_for_sequence.outerHTML)
Output:
<select >
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
Expected output:
<select value="2" >
<option>1</option>
<option selected>2</option>
<option>3</option>
<option>4</option>
</select>
I really can't find what I am doing wrong.
CodePudding user response:
You can use the setAttribute() method. It just takes two arguments: the attribute you want to add and its value.
for (i = 1; i <= 4; i ) {
let option = document.createElement("option");
option.text = i;
if (i == 2) {
option.setAttribute('selected','');
}
select_menu_for_sequence.appendChild(option);
}
or
option.setAttribute('selected','true');
CodePudding user response:
Update
In order to see "selected" in HTML use an attribute method instead of treating it like a property with dot notation.
select.options[2].toggleAttribute("selected");
Using dot notation on selected
makes it a property which doesn't show in HTML yet it is evident that .option[2]
has been selected.
select.options.selectedIndex = 2;
I think you neglected to append the select to <body>
or anything on the document.
const select = document.createElement("select");
select.classList.add("sequence");
document.body.append(select);
for (let i=1; i < 5; i ) {
let option = document.createElement("option")
option.textContent = i
select.append(option);
}
//select.options.selectedIndex = 2;
select.options[2].toggleAttribute("selected");
console.log(select.outerHTML);
CodePudding user response:
Check this
let select_menu_for_sequence = document.createElement("select");
select_menu_for_sequence.classList.add("sequence");
for (i = 1; i <= 4; i )
select_menu_for_sequence.options[select_menu_for_sequence.options.length]=new Option(i, i);
if (i == 2)
select_menu_for_sequence.options[select_menu_for_sequence.options.length]=new Option(i, i,true,true);
console.log(select_menu_for_sequence)
CodePudding user response:
Set the value of the <select>
element to the value of the selected option.
select_menu_for_sequence.value = 2;