How to get data attribute value for selected option

By FoxLearn 10/17/2024 9:04:14 AM   229
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.

For example

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

jquery data attribute

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

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

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

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

Here's a breakdown of the code:

$('#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.

This approach allows you to easily access custom data attributes for selected options.