我有一个选择下拉列表。我想获取所选选项的html
<select id="filter" multiple="multiple">
<option>Yes</option>
<option>No</option>
</select>
例如,如果我选择“是”和“否”,我希望输出为
<option>Yes</option>
<option>No</option>
答案 0 :(得分:2)
使用ECMAScript
可以很容易地做到这一点。
let select = document.getElementById('filter');
select.addEventListener('change', event => {
let checkedOption = [...event.target.children].find(c => c.selected);
console.log(checkedOption.outerHTML);
});
<select id="filter" multiple="multiple">
<option>Yes</option>
<option>No</option>
</select>
答案 1 :(得分:1)
function fun(e){
var concat='';
for(var i = 0; i<e.children.length; i++)
{
var str = e.children[i].outerHTML
concat +=str;
}
console.log(concat);
}
<html>
<head>
<title>JavaScript Popup Example 3</title>
</head>
<body>
<select id="filter" multiple="multiple" onChange='fun(this)'>
<option>Yes</option>
<option>No</option>
</select>
</body>
</html>
答案 2 :(得分:0)
如果要在控制台中输出,请继续。不需要jQuery。
filter.addEventListener('change', function() {
console.log([...this.querySelectorAll(':checked')]);
// even simpler but not available in IE 11:
console.log([...filter.selectedOptions]);
})
<select id="filter" multiple="multiple">
<option>Yes</option>
<option>No</option>
</select>
如果您想要的是所选项目中的值,只需向:checked
元素询问其textContent
:
filter.addEventListener('change', ()=>{
console.log([...filter.querySelectorAll(':checked')].map(i=>i.textContent));
})
<select id="filter" multiple="multiple">
<option>Yes</option>
<option>No</option>
</select>
答案 3 :(得分:0)
您可以像这样使用jQuery。
$("#filter").on('change', function(){
// the next line will find all the options which are selected
options = $(this).find('option:selected');
// loop through all the selected options and print them to console
for(var i = 0; i < options.length; i++){
option = options[i];
console.log(option.outerHTML);
}
});
select{
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="filter" multiple="multiple">
<option>Yes</option>
<option>No</option>
</select>
答案 4 :(得分:0)
Getting the selected values in a multiselect tag in Javascript中有一个类似的问题
您可以使用element.selected
命令找到选定的OPTION元素。简而言之,用于查找这些HTML元素的函数将如下所示:
var list = document.getElementById("filter");
var button = document.getElementById("button");
button.addEventListener("click", function(e){
for(var i=0; i<list.length; i++){
if(list.options[i].selected) {
console.log(list.options[i]);
};
};
});
答案 5 :(得分:0)
Using jquery you can get your desired output.
$(document).on('change', '#filter', function(){
$.each($(this).find('option:selected'), function(i,d){
console.log(d);
})
});