How to get data attribute value for selected option
By Tan Lee Published on May 31, 2024 3.28K
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
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Portal HTML Bootstrap
Nov 13, 2024
Responsive Admin Dashboard Template
Nov 11, 2024
Simple Responsive Login Page
Nov 11, 2024