How to get data attribute value for selected option
By FoxLearn 2/13/2025 2:01:19 AM 2.33K
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
<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> <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" 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.
Categories
Popular Posts
Stisla Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024
Portal HTML Bootstrap
11/14/2024