The following code returns 'undefined'...
$('select').change(function(){ alert($(this).data('id')); }); <select> <option data-id="1">one</option> <option data-id="2">two</option> <option data-id="3">three</option> </select>
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).
You can use this jquery data() syntax for get data-id attribute value. $("selector"). data("textval"); You can use this jquery data() syntax for get data-textval attribute value.
The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
You need to find the selected option:
$(this).find(':selected').data('id')
or
$(this).find(':selected').attr('data-id')
although the first method is preferred.
Try the following:
$('select').change(function(){ alert($(this).children('option:selected').data('id')); });
Your change subscriber subscribes to the change event of the select, so the this
parameter is the select element. You need to find the selected child to get the data-id from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With