drunkcamel
drunkcamel

Reputation: 915

How initialize dropdown (<select/>) with preselected value and then change it?

I've got a grid with dropdown in every row and I need to render it's state from DB. So I've got dropdowns defined like that with selected option specified for preselecting the value from DB.

<select id='selectId'>
<option value='1'>Option 1</option>
<option value='2' selected='selected'>Option 2</option>
<option value='3'>Option 3</option>
</select>​

The problem is in that when I change the value of a dropdown defined like that in a browser it changes on UI but selected attribute don't move and stays where it was. So when I then call $("#selectId").val() I get the old one value.

What's the appropriate way to initialize dropdown control and then have an ability to freely change it's value in browser or by jQuery?

Upvotes: 1

Views: 33333

Answers (6)

Jamie
Jamie

Reputation: 111

if you would like to set it value '2' on loading the webpage.

<script>
    $(document).ready(function () {
      $('#selectId').val('2');
    });
</script>

Upvotes: 0

icyrock.com
icyrock.com

Reputation: 28618

This seems to be working fine (Firefox on Ubuntu):

HTML

<select id='selectId'>
<option value='1'>Option 1</option>
<option value='2' selected='selected'>Option 2</option>
<option value='3'>Option 3</option>
</select>

JS

$('#selectId').change(function() {
    var opt = $(this).find('option:selected');
    console.log([opt.val(), opt.text()]);   
});

var opt_sel = $('#selectId option:selected');
opt_sel.val(99);
opt_sel.text('Changed option');

If you select the options, you'll see that it will print the changed version. Working example:

Hope this helps.

Upvotes: 2

sam_13
sam_13

Reputation: 532

please use this code instead,

$('#selectId option:selected').val(); 

Upvotes: 0

maxijb
maxijb

Reputation: 531

You can get the val of the option selected, instead of the select

$('select#selectId option:selected').val(); 

Docs: http://api.jquery.com/val/

Upvotes: 1

Raul Agrait
Raul Agrait

Reputation: 6018

Which browser are you trying this in? Your code looks fine to me, and appears to be working in this jsFiddle.

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

It should work fine. May be you are not setting it correctly.

You should pass the value of the option to val() method to select it.

E.g $('#selectId').val('1'); will set first option as selected and afterwards calling $('#selectId').val() will give you 1 and not 2.

Here is the working example http://jsfiddle.net/3eu85/

Upvotes: 2

Related Questions