[英]select data attribute of option using jquery
I am using a jQuery Plugin select2.js . 我正在使用jQuery插件select2.js 。 how can i select data attribute of selected option using jQuery.
如何使用jQuery选择所选选项的数据属性。
here is the code 这是代码
<select class="select2">
<option data-id="1" value="2"> CASE 1 </option>
<option data-id="2" value="2"> CASE 1 </option>
<option data-id="3" value="2"> CASE 1 </option>
</select>
$(document).ready(function(){
$('.select2').select2();
$('.select2').click(function(){
//alert($(this).val());
});
});
How i can get data-id
of selected option using jQuery. 我如何使用jQuery获取所选选项的
data-id
。
This has the same logic as select element. 这与选择元素具有相同的逻辑。 You can use default selectors.
您可以使用默认选择器。
$('.select2').change(function(){
alert($(this).find('option:selected').data('id'))
});
But i recommend you to use change event instead of click on select boxes. 但是我建议您使用更改事件,而不要单击选择框。
这将为您提供数据属性
$(this).data("id")
You can find selected option using :selected
selector and then use .data()
to get/set data attribute value. 您可以使用
:selected
选择器找到选定的选项,然后使用.data()
获取/设置数据属性值。 you should also use change event instead of click event for select element: 您还应该对选择元素使用change事件而不是click事件:
$('.select2').change(function(){
var selecteddataid = $(this).find('option:selected').data('id');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.