Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected option of select box

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?

like image 756
UpCat Avatar asked Jan 13 '11 12:01

UpCat


People also ask

How do I set the default option in select?

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.

How do I change the Select option?

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.

How do I add options to select box?

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.


2 Answers

This definitely should work. Here's a demo. Make sure you have placed your code into a $(document).ready:

$(function() {     $("#gate").val('gateway_2'); }); 
like image 75
Darin Dimitrov Avatar answered Sep 23 '22 03:09

Darin Dimitrov


$(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 }); 
like image 21
Zkoh Avatar answered Sep 21 '22 03:09

Zkoh