Reputation: 69
I have multiple selects with multiples options and i would like to group every option selected in an ul..
I've try this => https://jsfiddle.net/Lvywpaq6/ but not working... :(
<select id="select1" class="my-select">
<optgroup label="None">
<option>No thanks</option>
</optgroup>
<optgroup label="1">
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</optgroup>
<optgroup label="2">
<option>Test4</option>
<option>Test5</option>
<option>Test6</option>
</optgroup>
<optgroup label="3">
<option>Test7</option>
<option>Test8</option>
<option>Test9</option>
</optgroup>
</select>
<select id="select2" class="my-select">
<optgroup label="None">
<option>No thanks</option>
</optgroup>
<optgroup label="1">
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</optgroup>
<optgroup label="2">
<option>Test4</option>
<option>Test5</option>
<option>Test6</option>
</optgroup>
<optgroup label="3">
<option>Test7</option>
<option>Test8</option>
<option>Test9</option>
</optgroup>
</select>
<div>
<ul class="my-ul"> </ul>
</div>
I would like to know how can I create a group of li
with all of my selected option, dynamically ? And, btw, when I switch one option, I would like to update his li
, not add another one.
Upvotes: 1
Views: 697
Reputation: 93601
JSFiddle: https://jsfiddle.net/TrueBlueAussie/Lvywpaq6/1/
$(function() {
var $list = $('.my-ul');
$('.my-select').change(function() {
$list.empty();
$("select.my-select option:selected").each(function() {
var text = $(this).text();
$('<li>').text(text).appendTo($list);
});
});
});
If you only want to see selected options, test for "No thanks":
JSFiddle: https://jsfiddle.net/TrueBlueAussie/Lvywpaq6/3/
If you want initial selections shown later, fire a change
event at the end:
$(function() {
var $list = $('.my-ul');
$('.my-select').change(function() {
$list.empty();
$("select.my-select option:selected").each(function() {
var text = $(this).text();
if (text != "No thanks"){
$('<li>').text(text).appendTo($list);
}
});
}).change();
});
Upvotes: 1
Reputation: 28621
What you had was close.
Updated fiddle: https://jsfiddle.net/Lvywpaq6/2/
When I switch one option Extract your update function into a separate function so it can be called on change and startup.
And add .empty()
to clear previous results.
function update() {
$(".my-ul").empty();
$("select.my-select option:selected").each(function (){
var text = $(this).text();
$('<li>'+text+'</li>').appendTo('.my-ul');
})
}
$(function() {
$("select").change(update)
update();
});
Upvotes: 0