Reputation: 25
I am having trouble with showing selected options as a list. How can I loop through selected options in multi select drop down at the change event of select
here shows only one option selected as I'm not getting any idea of looping through selected options
<select class="form-control selectpicker sel3" multiple data-live-search="true" id="sel3" name="course[]">
<option value="1">Disciplinary Procedure</option>
<option value="2">Office Methods</option>
<option value="3">Photoshop</option>
<option value="4">CIGAS</option>
<option value="5">Auditing</option>
</select>
$(document).ready(function() {
$("#sel3").change(function() {
var x = document.getElementById("sel3");
var i = x.selectedIndex;
document.getElementById("demo").innerHTML= x.options[i].text;
});
});
if first two options selected, shows only first option
Upvotes: 0
Views: 712
Reputation: 41885
If I read your question correctly, you mean the text label of the option tags. Just iterate on each selected option like so using .each()
method:
$('#sel3').on('change', function() {
var selectedTexts = [];
$('#sel3 option:selected').each(function(i, selectedOptions) {
selectedTexts.push($(selectedOptions).text());
});
console.log(selectedTexts);
});
If you want the data in the value attribute, use $(selectedOptions).val()
instead.
To make the array items into comma separated list use selectedTexts.join();
and assign it as $('#demo').html( selectedTexts.join() )
Upvotes: 1
Reputation: 303
I made an example without jQuery, concatenating selected options as a string into the demo element. Hope it helps.
var select = document.getElementById("sel3");
select.onchange = () => {
let selected = [];
for (let i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
selected.push(select.options[i].text);
}
}
document.getElementById("demo").innerHTML = selected.join(', ');
}
<select class="form-control selectpicker sel3" multiple data-live-search="true" id="sel3" name="course[]">
<option value="1">Disciplinary Procedure</option>
<option value="2">Office Methods</option>
<option value="3">Photoshop</option>
<option value="4">CIGAS</option>
<option value="5">Auditing</option>
</select>
<p id="demo">
Selections
</p>
Upvotes: 0
Reputation: 824
Here is an example of jQuery
$(document).ready(function() {
$("#sel3").change(function() {
var html = "";
$("#sel3 option:selected").each(function(){
html += $(this).val() + $(this).text() + "<br/>";
});
$("#demo").html(html);
});
});
Upvotes: 0