Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically set the value of a select box element using JavaScript?

I have the following HTML <select> element:

<select id="leaveCode" name="leaveCode">   <option value="10">Annual Leave</option>   <option value="11">Medical Leave</option>   <option value="14">Long Service</option>   <option value="17">Leave Without Pay</option> </select> 

Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?

like image 356
brasskazoo Avatar asked Sep 17 '08 01:09

brasskazoo


People also ask

How do you set the value of a select element?

Use the value property to set the value of a select element, e.g. select. value = 'new value' . The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }


1 Answers

You can use this function:

selectElement('leaveCode', '11')  function selectElement(id, valueToSelect) {         let element = document.getElementById(id);     element.value = valueToSelect; } 
like image 50
Mitchel Sellers Avatar answered Oct 06 '22 01:10

Mitchel Sellers