Reputation: 1
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
alert(str);
})
Its supposed to alert the option of the selected options like "Grass Dirt Bushes"
Instead i am getting blank.
Upvotes: 0
Views: 540
Reputation: 86403
There is an easier way to do this with $('select').val()
<script type="text/javascript">
$(document).ready(function(){
alert ($("select").val());
$("select").change(function () {
var str = $("select").val();
alert(str);
})
})
</script>
The results are separated by commas, so the initial alert will show Shrubs,Bushes
Upvotes: 1
Reputation: 99328
This will work:
<script>
$(function(){
$("select").change(function () {
var str = $(this).children('option[selected]').text();
alert(str);
})
});
</script>
No need to do it for each option, just take the relevant options as children of the select, and text() will concatenate all that match.
Upvotes: 1