Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  145] [ 3]  / answers: 1 / hits: 25019  / 14 Years ago, wed, december 1, 2010, 12:00:00

i have



<select id=x>
<option value=5>hi</option>
<option value=7>hi 2</option>
</select>


I want a javascript function that enables me to select and display the <option> as default one by id. In other words, I want to do a setOption(5) and the <option> with the value 5 to be displayed in the combobox as a default .



Is that possible?


More From » html

 Answers
129

If you can, with ES6...



function setOption(selectElement, value) {
return [...selectElement.options].some((option, index) => {
if (option.value == value) {
selectElement.selectedIndex = index;
return true;
}
});
}


...otherwise...



function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}

setOption(document.getElementById('my-select'), 'b');


See it!



If it returns false, then the value could not be found :)


[#94779] Sunday, November 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;