Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On select change, get data attribute value

Tags:

jquery

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> 
like image 385
userBG Avatar asked Dec 01 '11 17:12

userBG


People also ask

How do you get the value of a data attribute?

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.

How do I get the value of a select tag?

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

How get value from data attribute in jQuery?

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.

What are data attributes in HTML?

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.


2 Answers

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.

like image 165
Jordan Brown Avatar answered Sep 21 '22 13:09

Jordan Brown


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.

like image 41
Rich O'Kelly Avatar answered Sep 24 '22 13:09

Rich O'Kelly