I want to set a option that was selected previously to be displayed on page load. I tried it with the following code:
$("#gate").val('Gateway 2');
with
<select id="gate"> <option value='null'>- choose -</option> <option value='gateway_1'>Gateway 1</option> <option value='gateway_2'>Gateway 2</option> </select>
But this does not work. Any ideas?
The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property. This is the easiest and most straightforward way of updating a select box state.
Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.
This definitely should work. Here's a demo. Make sure you have placed your code into a $(document).ready
:
$(function() { $("#gate").val('gateway_2'); });
$(document).ready(function() { $("#gate option[value='Gateway 2']").prop('selected', true); // you need to specify id of combo to set right combo, if more than one combo });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With