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 = () => {_x000D_
_x000D_
$('#leaveCode').val('14'); _x000D_
_x000D_
}_x000D_
_x000D_
const querySelectorFunction = () => {_x000D_
_x000D_
document.querySelector('#leaveCode').value = '14' _x000D_
_x000D_
}_x000D_
_x000D_
const getElementByIdFunction = () => {_x000D_
_x000D_
document.getElementById('leaveCode').value='14' _x000D_
_x000D_
}
_x000D_
input {_x000D_
display:block;_x000D_
margin: 10px;_x000D_
padding: 10px_x000D_
}
_x000D_
<select id="leaveCode" name="leaveCode">_x000D_
<option value="10">Annual Leave</option>_x000D_
<option value="11">Medical Leave</option>_x000D_
<option value="14">Long Service</option>_x000D_
<option value="17">Leave Without Pay</option>_x000D_
</select>_x000D_
_x000D_
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />_x000D_
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />_x000D_
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_