Reputation: 4116
whats wrong with my code?
Why i don't get options value(in my sample - 1)?
<script type="text/javascript">
$(document).ready(function(){
if ($("#number option:selected").length > 0)
{
alert('selected id:' + $("#number option:selected"));
}
});
</script>
<body>
<select id = "number" name = "number">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
Upvotes: 1
Views: 4374
Reputation: 630559
It doesn't work because you're trying to alert the jQuery object itself, not the value that's selected.
Instead use .val()
like this:
$(document).ready(function(){
alert('selected id:' + $("#numberd").val());
});
This will get the value of the select. If you want the text (e.g. "one") then use .text()
, like this:
$(document).ready(function(){
alert('selected id:' + $("#numberd option:selected").text());
});
The first <option>
will always be selected if nothing else is, so there's no need to check the .length
of matches here.
Upvotes: 3
Reputation: 322542
That only returns the element. You need to get the value
property of the element.
You can use jQuery's .val()
method to get the value.
alert( 'selected id:' + $("#number option:selected").val() );
And actually, you can call .val()
on the <select>
element itself instead of getting the selected <option>
.
alert( 'selected id:' + $("#number").val() );
Upvotes: 2