Prasoon
Prasoon

Reputation: 435

jquery - selecting an 'Option' in dynamically generated 'Select'

How do we select an 'Option' in 'Select' using jQuery?

$('#s_choice').selectedIndex = 1;//select 2nd item

Not working. JsFiddle is at http://jsfiddle.net/yesprasoon/pduX7/

Upvotes: 1

Views: 1478

Answers (5)

krishwader
krishwader

Reputation: 11381

In your fiddle, I've changed two things :

  • Changed $('#s_choice').selectedIndex = 1; to $('#s_choice').prop("selectedIndex", 1);. For selectedIndex to work like the way you've made it to be, you need a DOM object, not a jQuery object.
  • Changed the option where you choose where you want your scripts to be placed from onLoad to no wrap - in <body>. That means that your scripts will be placed in body. Scripts must always be placed in order for them to work. So no refresh is needed. for trivial changes such as setting the default value you needn't use a refresh method.

And Voila! It works :)

Here's your updated demo

Upvotes: 1

PSL
PSL

Reputation: 123739

Just add a refresh, also you can use either prop on jquery object or access the DOM element property like this $('#s_choice')[0].selectedIndex

$('#s_choice').prop('selectedIndex', 1);
$('#s_choice').selectmenu('refresh'); 

Or just chain it through

$('#s_choice').prop('selectedIndex', 1).selectmenu('refresh').change();

Demo

Reason being, selectmenu is a JQM widget so after setting the property on the actual select element you would need to do a refresh on it to refresh the widget.

Here is the documentation.

Upvotes: 4

CME64
CME64

Reputation: 1672

[updated & fiddle added]

Try this, it will definitely change your selection and update the ui:

$('#s_choice').children(':eq(1)').attr('selected','selected').change();

place your index between the brackets in eq , ex : ..(':eq(0)')..

JSFiddle

Upvotes: 1

Daniel Nill
Daniel Nill

Reputation: 5747

give your options different ids or classes then you can do $('#s_choice').find('#option3').attr("checked", true)

Upvotes: 1

David Thomas
David Thomas

Reputation: 253496

Try:

$('#s_choice')[0].selectedIndex = 1;

Or:

$('#s_choice').prop('selectedIndex', 1);

Or simply:

document.getElementById('s_choice').selectedIndex = 1;

The problem you have is that selectedIndex is a property of the DOM node, not the jQuery object.

Upvotes: 1

Related Questions