2016-07-22 55 views
0

想要从选定的下拉选项中获取数据属性值。如何在JavaScript中获取选项标签的数据属性

<select name="selection" id="mySelect"> 
    <option value="21" data-rc="25" data-clnc="10">Treatment</option> 
</select> 

var rc = ? //value of data-rc 
var clnc = ? //value of data-clnc 

没有jQuery,请只有JavaScript :)

+0

https://developer.mozilla.org/en-US/docs/Web/得到attribtues API/HTMLElement /数据集 – Andreas

回答

5

您可以通过dataset property读出来。

var option = document.getElementsByTagName("option")[0]; 
 

 
console.log(option.dataset.rc) 
 
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>

或者,如果你想获得所选选项的值:

var selection = document.getElementById("mySelect"); 
 

 
selection.onchange = function(event){ 
 
    var rc = event.target.options[event.target.selectedIndex].dataset.rc; 
 
    var clnc = event.target.options[event.target.selectedIndex].dataset.clnc; 
 
    console.log("rc: " + rc); 
 
    console.log("clnc: " + clnc); 
 
};
<select name="selection" id="mySelect"> 
 
<option value="21" data-rc="25" data-clnc="10">Treatment</option> 
 
<option value="21" data-rc="23" data-clnc="30">Treatment1</option> 
 
<option value="21" data-rc="31" data-clnc="50">Treatment2</option> 
 
<option value="21" data-rc="14" data-clnc="75">Treatment3</option> 
 
</select>

+0

索引并不总是为0 :( –

+0

)如果你想得到所选择的选项的值,我编辑了答案,如果你想获得所有的值,必须迭代。无论如何,现在你得到了一般想法。 –

0

你可以做到这一点与jQuery选择

var rc = $('select option:selected').data('rc'); 
0

$(选择).find( “选项:选择”)。数据( “RC”)为CLNC RC和CLNC其中选择是你的 “选择” 标签ID /类

+1

没有jQuery请只有JavaScript –

0

假设我们有一个选择现场

<select id="ddlViewBy"> 
     <option value="1" data-rc="25" data-clnc="10" selected="selected">test1</option> 
     <option value="2" >test2</option> 
     <option value="3">test3</option> 
    </select> 

现在,我们将获得选择列表和其选定的选项

var e = document.getElementById("ddlViewBy"); 
    var option= e.options[e.selectedIndex]; 

现在我们所选择的选项,我们可以得到它的attribtues

var attrs = option.attributes; 

attrs是属性数组,您可以通过索引得到属性数组。

或者您也可以通过

var datarc = option.getAttribute("data-rc"); 
0

检查这个工作钢笔

working pen

$('#options').on('change', function(){ 
    alert($(this).find("option:selected").attr('data-rc')) 
    alert($(this).find("option:selected").attr('data-clnc')) 
}); 
+2

没有jQuery请只有JavaScript –

+0

好的...等等,我会用本机代码 –

+0

更新的笔: http://codepen.io/ritesh14887/pen/WxzPEj –

相关问题