admin管理员组文章数量:1279008
I have a multi select element in jQuery.
Here is an example.
<select multiple id="multiple">
<option value="1" type="Alice">Option 1</option>
<option value="2" type="Bob">Option 2</option>
</select>
I know I can get all the values that are selected by doing $("#multiple").val();
How can I also get the type attributes of the selected options?
I have a multi select element in jQuery.
Here is an example.
<select multiple id="multiple">
<option value="1" type="Alice">Option 1</option>
<option value="2" type="Bob">Option 2</option>
</select>
I know I can get all the values that are selected by doing $("#multiple").val();
How can I also get the type attributes of the selected options?
Share Improve this question edited Jul 26, 2017 at 8:28 Suneel Kumar 1,6642 gold badges21 silver badges31 bronze badges asked Jun 25, 2014 at 1:20 RagHavenRagHaven 4,34725 gold badges75 silver badges114 bronze badges 1-
With HTML5 you can use
.selectedOptions
; it's a collection ofOption
elements from which you can get the attribute values. – Ja͢ck Commented Jun 25, 2014 at 1:40
5 Answers
Reset to default 3You need uses a pseudo option:selected
and look every option selected:
$('#multiple').change(function(){
var $value =$('option:selected',this).attr('type');
console.log($value);
});
Or using the .each()
like:
$('#multiple option:selected').each(function(){
var $value =$(this).attr('type');
console.log($value);
});
DEMO
DEMO With .each()
Try this:
$(document).on("change", "#multiple", function(){
var ids = $(this).find('option:selected').map(function() {
return $(this).attr('type');
}).get();
console.log(ids);
});
JSFiddle:
http://jsfiddle/LFMG7/2/
Probably the easiest is to use .map()
:
var types = $('#multiple > option:selected').map(function() {
return this.getAttribute('type');
}).get();
Demo
var t = document.getElementById('multiple'), a = [], i;
for(i = 0; i < t.length; i++) {
if(t[i].selected) a.push(t[i].getAttribute('type'));
}
// tested on IE8+, Chrome (Windows & Linux), Safari, Firefox (Windows & Linux), Opera
Fiddle
Perhaps something like this:
var myList = array();
$('#multiple option:selected').each(function(){
myList.push({"val":$(this).val(), "type":$(this).attr("type")});
});
本文标签: javascriptgetting attribute values from selected options in multiselectStack Overflow
版权声明:本文标题:javascript - getting attribute values from selected options in multiselect - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741210052a2358933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论