- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I get the selected value of a drop-down list with jQuery?
With jQuery, it’s easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.
Example
You can try to run the following code to learn how to change the selected value of a drop-down list. Here, we have a default select option first, but the alert shows the second option, which have been changed using the val method():
<html> <head> <title>jQuery Selector</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#button1").click(function(){ $("#myselection").val('2'); alert( $("#myselection option:selected").text() ); }); }); </script> </head> <body> <div> <p>The selected value:</p> <select id="myselection"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> </select> </div> <button id="button1">Click</button> </body> </html>
Advertisements