Custom data attribute not working inside <select> tag

dom, html, jquery

Solution

The data attribute belongs to the option element, but the change handler is registered to the select element so `this` inside the change handler refers to the select element which does not have the `data-*` attribute

You need to find the actual `option` element which was selected(you can use the :selected-selector) to do that.

Also use the .data() api to read the value of `data-*`

$(document).ready(function () {
    $(".myselect").change(function () {
        alert($(this).find('option:selected').data('spacing'));
    });
});

Demo: Fiddle

Problem

See this code: ``` <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <script src="Template/js/jquery-1.9.0.min.js" ></script> <script> $(document).ready(function(){ $(".myselect").change(function(){ alert( $(this).attr('data-spacing') ); }); }); </script> </head> <body> <select name="type" class="myselect"> <option data-spacing="001" value="" selected >Select A Camera</option> <option data-spacing="002" value="Nicon_D500">Nicon D500</option> <option data-spacing="004" value="Nicon_D600">Nicon D600</option> <option data-spacing="003" value="Canon_S900">Canon S900</option> </select> </body> </html> ``` The `data-custom` attribute is working for anything, but it's not working for `<select>` and `<option>` tags. This source code returns "Undefined" Please help me.

Original source