Home  >  Article  >  Web Front-end  >  How to Programmatically Set a Select Box Value in JavaScript?

How to Programmatically Set a Select Box Value in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 00:17:10102browse

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;
}

Consider the following HTML <select> element:

<select>

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

selectElement('leaveCode', '11');

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!

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