Reputation: 13740
My select element in my HTML is as below;
<select id="ddlCats">
</select>
I use jQuery to fill it on $(document).ready
:
// some ajax call
$.each(msg.cats, function (i, cat) {
$('#ddlCats').append(
$('<option></option>').val(cat.catID).html(cat.catName)
);
});
this works fine and the list generates fine with:
<select id="ddlCats">
<option value="68" selected="selected">option 1</option>
<option value="59">option 2</option>
<option value="60">option 3</option>
<option value="62">option 4</option>
</select>
until up to a point where I try to access the selected item's value with:
$('#ddlCats').val();
which always `returns 0. I also tried other avaliable selectors with no luck.
any ideas?
Upvotes: 1
Views: 9684
Reputation: 1517
You can get latest value by subscribing to onchange event:
var i = [1,2,3,4,5,6,7];
for(var a = 0; a < 6; a++){
$('#ddlCats').append($('<option></option>').val(i[a]).html(i[a]));
};
$('#ddlCats').change(function() {
$('#test').text($('#ddlCats').val());
})
Html is like something like this:
<select id="ddlCats">
</select>
<div id="test"></div>
Upvotes: 1
Reputation: 29658
select
elements are always annoying. Try this:
$("#ddlCats option:selected").val();
Upvotes: 5