Get attributes values from select2 selected option

39,558

Solution 1

obj = $("#dropdown").select2("data")

in obj variable i will get all the data of the selected node.

Solution 2

This was answered in another SO question

There is no direct method with select2, you can use a combinaison of select2 data and jQuery :

$("#example").select2().find(":selected").data("id");

First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.

Solution 3

We can use a combination of select2 data and jQuery :

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

Solution 4

var return_option = $("#your-select-input-id").select2().find(":selected")[0];    

above given statement will return select option and then put that return result as given below:

var name_of_attribute = $( return_option ).attr('name-of-attribute');

This will return the attribute value.

Solution 5

Following worked for me. Idea is to use "change" function as follows

<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
});
Share:
39,558
Leon van der Veen
Author by

Leon van der Veen

Updated on July 21, 2022

Comments

  • Leon van der Veen
    Leon van der Veen almost 2 years

    I'm using the Select2 plugin from http://ivaynberg.github.io/select2/select2-latest.html what works fine but i'm having a problem to get the values from the options attributes.

    I've got a select menu like this:

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

    How can I get the values of the attributes 'data-value', 'data-name' and 'value' of the selected option?

  • Jp Silver
    Jp Silver over 3 years
    Not working, obj = undefined. im using tags btw.
  • Jp Silver
    Jp Silver over 3 years
    Uncaught TypeError: can't access property 0, obj is undefined
  • Jp Silver
    Jp Silver over 3 years
    You sir, are my hero! I simplified it a bit by doing var obj = $($("#your-select-input-id").select2().find(":selected")[0])‌​; but either way works 100% :), I hate how they set this up.
  • felixmpa
    felixmpa about 3 years
    $("#example").select2('data')[0].element.attributes['data-na‌​me'].value it work for me.