showing results for - "add attribute in select option"
Griselda
04 Nov 2016
1<select id="select">
2  <option value="1" data-foo="dogs">this</option>
3  <option value="2" data-foo="cats">that</option>
4  <option value="3" data-foo="gerbils">other</option>
5</select>
6
7// JavaScript using jQuery
8$(function(){
9    $('select').change(function(){
10       var selected = $(this).find('option:selected');
11       var extra = selected.data('foo'); 
12       ...
13    });
14});
15
16// Plain old JavaScript
17var sel = document.getElementById('select');
18var selected = sel.options[sel.selectedIndex];
19var extra = selected.getAttribute('data-foo');
20