Suppose you have an HTML <select> element defined as:
<select>
You want to programmatically select the appropriate option in this list based on a given leaveCode number using JavaScript.
To achieve this, you can employ the following function:
function selectElement(id, valueToSelect) { let element = document.getElementById(id); element.value = valueToSelect; } selectElement('leaveCode', '11');
This function takes the ID of the select element ('leaveCode' in our case) and the desired value ('11' in the provided example) as parameters. It then programmatically sets the value property of the HTML <select> element to match the provided valueToSelect.
By using this function, you can dynamically select specific options in a select box element based on any criteria or conditions in your JavaScript code, providing greater flexibility and control over your HTML form elements.
The above is the detailed content of How Can I Programmatically Select an Option in a JavaScript Select Box?. For more information, please follow other related articles on the PHP Chinese website!