Tag Archives: jquery tutorial how to work with select options

JQuery: working with select options

We are going to start with the next simple html code

[html]

[/html]

How to get selected value

[javascript]
$(‘#opt option:selected’).val();
[/javascript]

How to get selected text

[javascript]
$(‘#opt option:selected’).text();
[/javascript]

How to set option by value

[javascript]
$(‘select#opt option[value=1]‘).attr(‘selected’,'selected’);
[/javascript]

If we need to set selected option by variable consider next code

[javascript]
var index = 1;
$(‘select#opt option[value=' + index +']‘).attr(‘selected’,'selected’);
[/javascript]

Next code might be applied if we need to set selected option by index

[javascript]
var content=”Boys”;
$(‘#opt option:contains(“‘+content+’”)’).attr(‘selected’,'selected’);
[/javascript]

Result: first option will be selected

One more piece of code to review:
[javascript]
$(‘select#optn_status option[value=4]‘).attr(‘disabled’, ‘disabled’);
[/javascript]