Home > Web Front-end > JS Tutorial > body text

How to Programmatically Set a Select Box Value in JavaScript?

Mary-Kate Olsen
Release: 2024-11-28 00:17:10
Original
102 people have browsed it

How to Programmatically Set a Select Box Value in JavaScript?

Programmatically Setting Select Box Value using JavaScript

To set the value of a <select> element based on a parameter, utilize the following JavaScript function:

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

Consider the following HTML <select> element:

<select>
Copy after login

To select the "Medical Leave" option (value "11"), call the function as follows:

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

This will programmatically set the value of the <select> element to "11".

The above is the detailed content of How to Programmatically Set a Select Box Value in 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