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

How Can I Select Dropdown Options Using JavaScript?

Susan Sarandon
Release: 2024-11-28 09:12:11
Original
1070 people have browsed it

How Can I Select Dropdown Options Using JavaScript?

Selecting Dropdown Option Values using JavaScript Functions

Consider the following HTML <select> element:

<select>
Copy after login

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;
}
Copy after login

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

selectElement('leaveCode', '11');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template