Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the SELECTED property of dropdown in jQuery?

I am sending the index number of dropdown's options that users selects from index. Now want to select that specific option as 'selected' on another view. How to make it using jQuery?

$('#book_selection').attr("disabled", "disabled");
$('#book_selection').selectedIndex = 1;

but its not working...

like image 891
Baqer Naqvi Avatar asked Jan 01 '14 11:01

Baqer Naqvi


People also ask

How can I set the value of a DropDownList using jQuery?

Use $('select[id="salesrep"]'). val() to retrieve the selected value. Use $('select[id="salesrep"]'). val("john smith") to select a value from dropdown.

How do I select a specific DropDownList using jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do you display a selected value in a drop down list?

STEP 1 − Create a select tag with multiple options and assign an id to the select tag. STEP 2 − Also, create an empty DOM with an id to display the output. STEP 3 − Let there be a button element for the user to click and see the option selected. STEP 4 − Let the user select an option from the dropdown list.


2 Answers

Use prop() method, setting selectedIndex to a jQuery object practically does nothing. As of jQuery 1.6 for modifying properties prop method should be used instead of attr method:

$('#book_selection').prop("disabled", true)
                    .prop('selectedIndex', 1);

Alternatives:

// Getting the DOM element object using bracket notation and `.get()` method
$('#book_selection')[0].selectedIndex = 1;
$('#book_selection').get(0).selectedIndex = 1;
like image 94
undefined Avatar answered Sep 18 '22 23:09

undefined


Use .prop() for setting the properties, By the way you are in need to set the value by using index, so in that case .eq(index) will help you.

Try,

$('#book_selection option').eq(1).prop('selected',true);
like image 31
Rajaprabhu Aravindasamy Avatar answered Sep 20 '22 23:09

Rajaprabhu Aravindasamy