How to get selected option in JQuery
By Tan Lee Published on Oct 17, 2024 260
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 use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- 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
Categories
Popular Posts
Bootstrap 4 Login Page Template
Nov 11, 2024
Responsive Admin Dashboard Template
Nov 11, 2024
RuangAdmin Template
Nov 13, 2024
Gentella Admin Template
Nov 14, 2024