繁体   English   中英

从选择框中获取选定的HTML文件

[英]Fetching the selected options html from select box

我有一个选择下拉列表。 我想获取所选选项的html

<select id="filter" multiple="multiple">
     <option>Yes</option>
     <option>No</option>
</select>

例如,如果我选择是和否,我希望输出为

<option>Yes</option>
<option>No</option>

使用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> 

 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> 

如果要在控制台中输出,请继续。 无需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> 

您可以使用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> 

在Javascript的multiselect标记中获取选定的值时,存在类似的问题

您可以使用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]);
    };
  };
});

https://jsfiddle.net/bgz2cr9w/

Using jquery you can get your desired output.


$(document).on('change', '#filter', function(){
    $.each($(this).find('option:selected'), function(i,d){
        console.log(d);
    })
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM