tags:

views:

77

answers:

2
  <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.

+1  A: 

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.

Eli
+1  A: 

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

fudgey
Actually the result of `$('select').val()` is an array. `alert()` just calls the `toString()` method, which joins the results with a comma. So you can do `alert($('select').val().join(' '))` to duplicate the questioner's code.
brianpeiris
Ahhh thanks for the clarification :)
fudgey