Skip to content

Instantly share code, notes, and snippets.

@diki-haryadi
Created April 26, 2021 03:03
Show Gist options
  • Select an option

  • Save diki-haryadi/8000773530c4218601a08fdca8fbe67c to your computer and use it in GitHub Desktop.

Select an option

Save diki-haryadi/8000773530c4218601a08fdca8fbe67c to your computer and use it in GitHub Desktop.
# html
<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>
# 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');
# sources
https://stackoverflow.com/questions/4564659/adding-additional-data-to-select-options-using-jquery/4564711
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment