-1

I want to select an option from an HTML <select> object using JavaScript. The select has 6 options and I know I can get the select object using:

document.getElementByID('id');

I don't know if that's common, but the options have a property named value, so how can I select an option by value or text?

1
  • Be aware case is important getElementById ! Commented Jun 15, 2021 at 15:05

1 Answer 1

1

You can get the options, loop and check the value

let select = document.getElementById("id");
for (let i = 0; i < select.options.length; i++) {
    if (select.options[i].value == "two") {
        select.selectedIndex = i;
        break;
    }
}

Demo: https://jsfiddle.net/ghyx623m/

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

1 Comment

You should know that this is a duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.