Reputation: 435
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
Reputation: 11381
In your fiddle, I've changed two things :
$('#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.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 :)
Upvotes: 1
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();
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
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)')..
Upvotes: 1
Reputation: 5747
give your options different ids or classes then you can do $('#s_choice').find('#option3').attr("checked", true)
Upvotes: 1
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