Adding additional data to select options using jQuery

HTML Markup

<select id="select">
  <option value="1" data-foo="dogs">this</option>
  <option value="2" data-foo="cats">that</option>
  <option value="3" data-foo="gerbils">other</option>
</select>

Code

// JavaScript using jQuery
$(function(){
    $('select').change(function(){
       var selected = $(this).find('option:selected');
       var extra = selected.data('foo'); 
       ...
    });
});

// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');

See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/

By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.

Leave a Comment