How to get data attribute value for selected option
By FoxLearn 3/10/2025 9:24:20 AM 2.79K
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 IDmySelect
..data('yourAttributeName')
retrieves the value of the data attribute namedyourAttributeName
from the selected option.
You to easily access custom data attributes for selected options.
Categories
Popular Posts
How to secure ASP.NET Core with NWebSec
11/07/2024
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024