How to get selected option in JQuery
By FoxLearn 10/17/2024 9:10:58 AM 182
To get the selected option from a dropdown using jQuery, you can use the :selected selector or the .val() method.
For example:
<select id="product"> <option value="1">Laptop</option> <option value="2">IPhone</option> </select> <button id="btn">Get Selected Option</button>
$('#id option:selected').text()
gets the text of the currently selected option.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('#btn').click(function() { var selectedOption = $('#id option:selected').text(); }); }); </script>
$('#id').val()
gets the value of the selected option.
$('#btn').click(function() { var selectedValue = $('#id').val(); });
You can choose either method depending on whether you need the value or the text of the selected option.
- How to format number with commas and decimal in Javascript
- How to Pass string parameter in an onclick function
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
- How to copy text to clipboard in Javascript
Categories
Popular Posts
Carpatin Admin Dashboard Template
11/17/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024