Home >Web Front-end >JS Tutorial >How Can I Select Dropdown Options Using JavaScript?

How Can I Select Dropdown Options Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 09:12:111077browse

How Can I Select Dropdown Options Using JavaScript?

Selecting Dropdown Option Values using JavaScript Functions

Consider the following HTML <select> element:

<select>

To select an appropriate option based on a provided leave code, create a JavaScript function:

function selectElement(id, valueToSelect) {    
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

To use this function, pass the element ID and desired option value as arguments:

selectElement('leaveCode', '11');

This code will set the dropdown (leaveCode) to "Medical Leave" by selecting the option with the value "11".

The above is the detailed content of How Can I Select Dropdown Options Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn