Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  100] [ 5]  / answers: 1 / hits: 97510  / 13 Years ago, tue, april 5, 2011, 12:00:00

I have a select element that allows for multiple selections. I'd like to display the selected values in another part of the page (in a div or something) as the user makes changes to what is selected.



Is the only way of doing this to iterate over the options and check if selected is true? this would not be preferable since each onchange event would require the entire select element to be iterated over.



Here's a fiddle that demonstrates how I am currently doing it, but I'm hoping maybe there's a better way than having to iterate over all the options on every change: multiple select elment onchange fiddle


More From » jquery

 Answers
4

.val() on a multiple select returns an array.



See the snippet below as an example:



$(function() {
$('#fruits').change(function(e) {
var selected = $(e.target).val();
console.dir(selected);
});
});

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>
<select multiple=true id=fruits>
<option value=apple>Apple</option>
<option value=banana>Banana</option>
<option value=mango>Mango</option>
<option value=grape>Grape</option>
<option value=watermelon>watermelon</option>
</select>




[#92903] Sunday, April 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ammonjesseg

Total Points: 170
Total Questions: 110
Total Answers: 98

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;