0

I would like to allow multiple selection of items so that the #par displays all 3 values selected with a shift. This post leads me to believe such functionality is not built in with jQuery, and needs a workaround, although it is from 3 years ago. I use jsFiddle and 1.9.1 jQuery.

<select id="select" multiple>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<br />
<p id="par"></p>
$('#select').change(function(){
    $('#select option:selected').each(function(){
        $("#par").text($(this).text() + ", ");
    });
});
Community
  • 1
  • 1
Turo
  • 1,537
  • 2
  • 21
  • 42

1 Answers1

2

You can get a comma separated list of the values chosen in a multiple select by using val() - the same as you would any other form element. Try this:

$('#select').change(function() {
    $("#par").text($(this).val());
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • thanks a lot Rory. I've been fiddling with this. How come the option:selected is skipped and it still works as expected? it looks like this code should list all the options, not only the ones selected (?) – Turo Feb 02 '16 at 20:23
  • It's simply because `val()` does all the work for you internally. It knows the type of element it's being called on, so gets the right value for the specific situation. – Rory McCrossan Feb 02 '16 at 20:33
  • ok thank you, checked the docs as well and it is actually there :) – Turo Feb 02 '16 at 20:43
  • Everything is. The jQuery documentation is about the best available, for anything :) – Rory McCrossan Feb 02 '16 at 20:44