Search code examples
javascriptjqueryhtmlcustom-data-attribute

How to get data-value of selected option on select change in jquery


My html syntax is as below

<select id="category" name="category">
  <option value="0">Please Select</option>
  <option value="50" data-value="akne">ACNE</option>
  <option value="11" data-value="rednessbumps">Redness / Bumps</option>
  <option value="15" data-value="sunspotsfreckles">Sunspots / Freckles</option>
  <option value="16" data-value="agingwrinkles">Aging / Wrinkles</option>
  <option value="17" data-value="dry-sensitive">Dry Sensitive</option>
</select>
$("#category").change(function () {
  var selectedItem = $(this).val();
  var abc=$(this).attr("data-value");
});

Here I am not able to get the data-value in jquery, How should I get that?


Solution

  • Use

    var abc = $('option:selected',this).data("value");
    

    Try

    $("#category").change(function() {
      var selectedItem = $(this).val();
      var abc = $('option:selected',this).data("value");
      alert(abc);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="category" name="category">
      <option value="0">Please Select</option>
      <option value="50" data-value="akne">ACNE</option>
      <option value="11" data-value="rednessbumps">Redness / Bumps</option>
      <option value="15" data-value="sunspotsfreckles">Sunspots / Freckles</option>
      <option value="16" data-value="agingwrinkles">Aging / Wrinkles</option>
      <option value="17" data-value="dry-sensitive">Dry Sensitive</option>
    </select>