How to get data attribute value for selected option

By FoxLearn Published on May 31, 2024   3K
To get the value of a data attribute for the selected option in a dropdown using jQuery, you can use the data() method along with the :selected selector.

Option JQuery attribute get

For example, jquery get data attribute value

<!-- example option attribute data jquery -->
<select id="ddlProduct" name="ProductId">
    <option value="1" data-name="phone">IPhone</option>
    <option value="2" data-name="phone">Samsung</option>
</select>

To get selected option data attribute value you can write your code as shown below.

For example, attribute selected jquery get

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
// jquery get data attribute from selected option
<script>
$(document).ready(function() {
    // jquery data attribute selected
    $('#ddlProduct').change(function () {
        // jquery get value of id
        var data = $("#ddlProduct option:selected").data("name"); // jquery data attribute
    });
});
</script>

using jquery get selected option data attribute as the following code.

// Assuming your select element has an id of "mySelect"
// selected option jquery attribute
var selectedOptionData = $('#mySelect option:selected').data('yourAttributeName');

In this example:

  • $('#mySelect option:selected') selects the currently selected option within the <select> element with the ID mySelect.
  • .data('yourAttributeName') retrieves the value of the data attribute named yourAttributeName from the selected option.

You to easily access custom data attributes for selected options.