Select <select> item by value
I have
<select id="x"> <option value="5">hi</option> <option value="7">hi 2</option> </select> I need a javascript function that allows me to select and display the default <option> by id. In other words, I want to make setOption(5) and <option> with the value "5", which will be displayed in the default combo box.
Is it possible?
+11
Ronan Dejhero Dec 01 '10 at 12:03
source share5 answers
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'); If it returns false , then this value cannot be found :)
+18
alex Dec 01 '10 at 12:10 2010-12-01 12:10
source shareUsing Javascript:
document.getElementById('drpSelectSourceLibrary').value = 'Seven'; +3
user5846985 May 25 '16 at 18:45 2016-05-25 18:45
source shareIf you are using jQuery (1.6 or higher)
$('#x option[value="5"]').prop('selected', true) +2
Dasun Jul 19 '13 at 10:52 on 2013-07-19 10:52
source shareIf someone is looking for a jquery solution, use the val() function.
$("#select").val(valueToBeSelected); In javascript
document.getElementById("select").value = valueToBeSelected; +1
Rajan Verma Jan 17 '18 at 18:33 2018-01-17 18:33
source shareYou don't even need to use javascript, just use the selected attribute:
<select id="x"> <option value="5" selected>hi</option> <option value="7">hi 2</option> </select> -2
fifigyuri Dec 01 '10 at 12:08 2010-12-01 12:08
source share