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

You can use this function:

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

selectElement('leaveCode', '11');
<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>

Optionally if you want to trigger onchange event also, you can use :

element.dispatchEvent(new Event('change'))

If you are using jQuery you can also do this:

$('#leaveCode').val('14');

This will select the <option> with the value of 14.


With plain Javascript, this can also be achieved with two Document methods:

  • With document.querySelector, you can select an element based on a CSS selector:

    document.querySelector('#leaveCode').value = '14'
    
  • Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:

    document.getElementById('leaveCode').value = '14'
    

You can run the below code snipped to see these methods and the jQuery function in action:

const jQueryFunction = () => {
  
  $('#leaveCode').val('14'); 
  
}

const querySelectorFunction = () => {
  
  document.querySelector('#leaveCode').value = '14' 
  
}

const getElementByIdFunction = () => {
  
  document.getElementById('leaveCode').value='14' 
  
}
input {
  display:block;
  margin: 10px;
  padding: 10px
}
<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>

<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>