select <select> item by value
Asked Answered
S

7

14

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?

Salchunas answered 1/12, 2010 at 12:3 Comment(5)
And what have you tried?Zaria
you shouldn't need even javascript for this. Is there any reason you need to have in done on the client side?Ancohuma
@Ancohuma - Why not? I can think of several reasons this can be useful. BTW, if jQuery is an option, it's as simple as $('#x').val('5');.Protagoras
@Protagoras clearly there might be reasons for that, but if there aren't then why not drop javascript from the solution? It just wasn't that clear from the question (for me) that javascript is really that important to have.Ancohuma
Refer this article : javascriptstutorial.com/blog/…Mobility
O
22

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

Occupier answered 1/12, 2010 at 12:10 Comment(6)
Thanks , Little fix for (var i = 0; i < options.length; i++) Salchunas
@Ronan Dejhero That fix isn't necessary ?Occupier
@Ronan Dejhero It will access the length property for every iteration though :)Occupier
optionsLength = options.length; outside the loop , then use optionsLength inside the loopSalchunas
Can it be done without using i-like indexes? via forEach somehow?Movie
@Movie Yep, but you'd need to use something like [].forEach.call() as the options is a NodeList, I'd imagine.Occupier
M
6

If someone looking for jquery solution, use the val() function.

$("#select").val(valueToBeSelected);

In Javascript,

document.getElementById("select").value = valueToBeSelected; 
Mucus answered 17/1, 2018 at 18:33 Comment(0)
C
3

If you are using jQuery (1.6 or greater)

$('#x option[value="5"]').prop('selected', true)
Cartagena answered 19/7, 2013 at 10:52 Comment(3)
When I try $('#x option[value="5"]') in js-console with my value (visible from inspecting the element), it does not find the option. If I use $('#x'), it does. All using my page's element ID, of course.Imtiaz
I replied to the question, the original question asked "select <select> item by value" What you are trying to do is something else. and thanks for the down vote for a correct answer :DCartagena
sorry for the misunderstand :) down vote and your comment both come at once, that's why I made a wrong calculation :)Cartagena
M
2

Using Javascript:

document.getElementById('drpSelectSourceLibrary').value = 'Seven';
Mobility answered 25/5, 2016 at 18:45 Comment(0)
R
0

vanilla JS:

Get index of search value

var index=[...document.getElementByID('name').options].find(o=>o.value==5).index

Set it:

document.getElementByID('name').selectedIndex=index;
Ruthy answered 25/10, 2022 at 14:59 Comment(0)
Q
-1

So I came across this and thought I'd offer a couple of solutions.

The easiest way for a single select, is just to set the value of the select:

var mySelect = document.getElementById( 'my-select-id' );
mySelect.value = 7;

You can also get the selected option by value just the same way:

console.log( mySelect.value );

What I was looking for was a better way to set the values of a multiselect (<select multiple>...</select>) but as it turns out - it seems you have to loop through the options, and set them in some kind of for loop:

function setMultiSelectValues( select, values ) {
    for (var i = 0; i < select.options.length; i++) {
        var option = select.options[i];
        if ( values.includes( option.value ) ) {
            option.selected = true;
        }
    }
}

And then use it like:

var mySelect = document.getElementById( 'my-select-id' );
var myValues = [ 'option-1', 'option-5' ];
setMultiSelect( mySelect , values );

Demo: https://codepen.io/rmorse/pen/QWNymdb

Quadriga answered 13/8, 2020 at 15:51 Comment(0)
A
-2

You should not need even javascript to get involved, use simply the selected attribute:

<select id="x">
  <option value="5" selected>hi</option>
  <option value="7">hi 2</option>
</select>
Ancohuma answered 1/12, 2010 at 12:8 Comment(2)
Actually i asked for a javascript code to be able to edit the object that has that "selected" attribSalchunas
@Ronan, yeah; but that's the point @Ancohuma was making: unless this is being done in response to user-actions on the client-side there's little reason to use a JavaScript function to achieve this.Zaria

© 2022 - 2024 — McMap. All rights reserved.