Home > Web Front-end > JS Tutorial > How Can JavaScript Programmatically Select Options in a Select Box?

How Can JavaScript Programmatically Select Options in a Select Box?

Patricia Arquette
Release: 2024-12-02 00:22:09
Original
180 people have browsed it

How Can JavaScript Programmatically Select Options in a Select Box?

Programmatic Selection of Options in Select Box Elements with JavaScript

In web development, dynamically setting the selected value of a select box element is often necessary. JavaScript provides a convenient method to achieve this.

Problem:

Consider the following HTML select box element:

<select>
Copy after login

How do we programmatically select the appropriate option based on a given leave code number (e.g., '11') using JavaScript?

Solution:

To select an option dynamically, we can use the following JavaScript function:

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

To use this function, simply pass the ID of the select box element ('leaveCode' in our case) and the value of the option you want to select (e.g., '11').

Example:

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

This will select the option with the value '11' (Medical Leave) in the select box.

The above is the detailed content of How Can JavaScript Programmatically Select Options in a Select Box?. 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