w3resource
jquery exercises

jQuery: How to get the selected value and currently selected text of a dropdown box?

jQuery Practical exercise Part - I : Exercise-34

How to get the selected value and currently selected text of a dropdown box using jQuery?

Sample Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>How to get the selected value and currently selected text of a dropdown box using jQuery?</title>
</head>
<body>
<select id="ddid">
<option id="op1" value="red">Red</option>
<option id="op2" value="green">Green</option>
<option id="op3" value="blue">Blue</option>
<option id="op4" value="white">White</option>
</select>
 <input id="button1" type="button" value="Click!" />
 </body>
 </html>

JavaScript Code:

$(document).ready(function(){ 
  $('#button1').click(function(){ 
   console.log($('#op2').val());
   console.log($('#op4').val());
  console.log($('#ddid :selected').text());
   });
});

See the Pen jquery-practical-exercise-34 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Delete all table rows except first one using jQuery.
Next: Disable a link using jQuery.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming