0

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
shanebp
  • 1,904
  • 3
  • 17
  • 28
  • Yes, I know that it works on each option. I'm asking how to get it from the select definition - to the right of the class? – shanebp May 18 '23 at 17:01
  • *Is it possible to get the data attribute value during an on change event?* - yes, your code does that. If you're asking something else, then please include what you're *actually* asking in the question, not as a comment or a code comment – freedomn-m May 18 '23 at 17:04
  • [This post](https://meta.stackoverflow.com/questions/425359/jquery-datatable-add-row-content-with-link) on Meta looks like it belongs here, not there. Can you repost it? – halfer Jun 27 '23 at 19:32
  • And that Meta post would be answered with this solution: [SO answer](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Jun 28 '23 at 07:33

1 Answers1

1

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132