[英]how to output the text of all selected options in a multi select drop-down list without submitting using php javascript
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
如何在select的change事件中遍历multi 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 如果选择了前两个选项,则仅显示第一个选项
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: 只需使用
.each()
方法来迭代每个选定的选项:
$('#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. 如果要在value属性中使用数据,请改用
$(selectedOptions).val()
。
To make the array items into comma separated list use selectedTexts.join();
要将数组项变成逗号分隔的列表,请使用
selectedTexts.join();
and assign it as $('#demo').html( selectedTexts.join() )
并将其分配为
$('#demo').html( selectedTexts.join() )
Here is an example of jQuery 这是jQuery的示例
$(document).ready(function() {
$("#sel3").change(function() {
var html = "";
$("#sel3 option:selected").each(function(){
html += $(this).val() + $(this).text() + "<br/>";
});
$("#demo").html(html);
});
});
I made an example without jQuery , concatenating selected options as a string into the demo element. 我创建了一个没有jQuery的示例,将所选选项作为字符串连接到demo元素中。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.