Search code examples
imageselectdropdownmaterialize

Get data-icon value from materialize select option


I have a simple icon-based dropdown using materialize like so:

<select id="eventopponent" onchange="enableWager(value);" class="icons " >
  <option value="" selected disabled >Select a friend</option>
  <option value="" data-icon="img/no-user.jpg" class="left">Invite New Friend</option>
  <option value="" data-icon="img/david.jpg" class="left">David X.</option>
</select>

In the onchange event I would like to get the data-icon for the selected option. I know how to find the selected option but retrieving the data-icon value is not clear to me.


Solution

  • Just in pure javascript, you can do it like this

    function enableWager(obj) {
      var icon = obj.options[obj.selectedIndex].getAttribute('data-icon');
      alert(icon);
    }
    <select id="eventopponent" onchange="enableWager(this);" class="icons " >
      <option value="" selected disabled >Select a friend</option>
      <option value="" data-icon="img/no-user.jpg" class="left">Invite New Friend</option>
      <option value="" data-icon="img/david.jpg" class="left">David X.</option>
    </select>