Search code examples
javascriptjqueryhtmlcustom-data-attributejquery-data

Get "data-something" from an <option> tag contained in <select>


I have this HTML

<select id="something">
    <option value="1" data-something="true">Something True</option>
    <option value="2" data-something-else="false">Something Else False</option>
</select>

And this jQuery snippet with which I'm trying to get the values from data-* attributes:

$(document).ready(function() {
    $('body').on('change', 'select#something', function() {
        console.log( $(this).data('something') ); // undefined always
        console.log( $(this).data('something-else') ); // undefined always too
    });
});

How to get data-* attribute values with jQuery?


Solution

  • this is the select element.

    console.log($(this).find(":selected").data("something"))