2013-10-03 63 views
5

我使用的是從http://ivaynberg.github.io/select2/select2-latest.html的Select2插件什麼工作正常,但我有問題從選項屬性中獲取值。從select2選擇選項獲取屬性值

我有這樣的選擇菜單:

<select name="invoice_line[0][vat]" class="vat"> 
    <option value="20440" data-value="21.00" data-name="20440" selected="selected">21%</option> 
    <option value="20441" data-value="6.00" data-name="20441">6%</option> 
    <option value="20442" data-value="0.00" data-name="20442">0%</option> 
</select> 

我怎樣才能獲得屬性「數據值」,「數據名」和所選擇的選項的「價值」的價值?

回答

0

不知道關於撐着,沒有檢查是否代碼工作我想這將是這樣的:

$('.vat li').each(function(){ 
    var me = $(this), 
    mevalue = me.attr('value'), 
    datavalue = me.data('value'), 
    dataname = me.data('name'); 

    //do what you want with the data? 
}); 
0

認沽選擇2到標記模式,它會幫助你。 或者 嘗試下面類似的代碼,它可能爲你工作...

$("$id").select2("val", option); 
$("$id").attr("data-name"); 
0

我知道這是一個古老的職位,但我有同樣的問題掙扎。這是我和我的好朋友蒂斯終於得到了工作的解決方案:

<script type="text/javascript"> 

$(document).ready(function() 
{ 
    $("#e1").select2(); 

    $("#e1").change(function() { 

     var theID = $("#e1").val(); 
     $('#staffNr').val(theID); 
     $('#staffNr').val(); 
      //var theID = $(test).select2('data').id; 
      var theSelection = $(test).select2('data').text; 
      $('#selectedID').text(theID); 
      $('#selectedText').text(theSelection); 
    }); 

}); 

@Html.Hidden("fieldName","staffNr"); 

這個工作在我的MVC 4觀點與我的HTML表格的最後一行在那裏它被正確添加到模型。不要忘了贊成票,如果你用我的答案,請:)我還沒有得到太大的聲譽......

5

another SO question

得到的回答是沒有與選擇2沒有直接的方法,您可以使用select2數據和jQuery組合:

$(「#example」)。select2()。find(「:selected」)。data(「id」);

首先你得到select2數據,然後你用jQuery找到你選擇的選項,最後是數據屬性。

0
el = document.getElementsByName("invoice_line[0][vat]") 
el.options[[el.selectedIndex]].attributes["data-id"].value 
0

我希望你解決了這個問題。在這裏,我們不使用select2(),如果我們用select2()它不會工作,其他所有功能,如formatNoMatches, on-change....

$("#example").find(":selected").data("id"); 
11
obj = $("#dropdown").select2("data") 

obj變量i會得到所有的selected nodedata

0

所選項目的params.data.element對象包含您正在查找的數據。

哪裏.foo是我打電話的選擇元素,我想訪問的選項中的數據屬性是data-bar="some value"對我來說,以下工作:

var $fooSelect = $('.foo'); 
$fooSelect.on(function (e) { 
    console.log($(e.params.data.element).data('bar')); 
}); 
1

我們可以使用選擇2個數據的組合和jQuery:

$("#example").select2('data').element[0].attributes['data-name'].value 
1

以下爲我工作。想法是使用「變更」功能如下

<select class="drop-down"> 
    <option value="0">A</option> 
    <option value="1">B</option> 
</select> 

$('.drop-down').select2().on("change", function(e) { 
    var obj = $(".drop-down").select2("data"); 
    console.log("change val=" + obj[0].id); // 0 or 1 on change 
});