jqueryselectorcustom-data-attribute

jQuery get data-id from selector onchange


Is it possible to get the data attribute value during an on change event?

jQuery(document).ready(function($) {
  $('.mystatus').on("change", function() {
    var value = this.value;
    alert(value);

    var myid = get the value of data-myid
    // myid should equal '123'
  });
});
<select class="mystatus" data-myid="123">
  <option value="No Status">No Status</option>
  <option selected="selected" value="Potential">Potential</option>
</select>

Solution

  • Since the data attribute exists on the <select>, access the data atribute using: $(this).data.

    $(function() {
      $('.mystatus').on('change', function() {
        var $select = $(this);
      
        var value = $select.val();
        console.log(value);
    
        var selectDataId = $select.data('myid');
        console.log(selectDataId);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select class="mystatus" data-myid="123" required>
      <option value="" selected disabled>-- Choose and option --</option>
      <option value="No Status">No Status</option>
      <option value="Potential">Potential</option>
    </select>