0
  <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
  • By "getting blank", do you mean that the alert dialog is blank or that the code is not running at all? Because your code seems to run fine: jsbin.com/atiba (jsbin.com/atiba/edit). Are you sure you put your JavaScript in the right place? Commented Oct 10, 2009 at 1:52

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.