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>
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; }
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');
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!