w3resource

jQuery: Find the specific option tag text value of a selected option

jQuery core : Exercise-4 with Solution

Find the specific option tag text value of a selected option.

Sample Data :


<body>
 <select id="myselect">
    <option value="1">Option-1</option>
	<option value="2">Option-2</option>
	<option value="3">Option-3</option>
	</select>
</body>
	

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Find the specific option tag text value of a selected option</title>
</head>
<body>
<select id="myselect">
    <option value="1">Option-1</option>
    <option value="2">Option-2</option>
    <option value="3">Option-3</option>
    </select>
</body>
</html>

JavaScript Code :

var txt = $("#myselect option[value=2]").text();
console.log(txt);

Sample Output:

"Option-2"

Live Demo:

See the Pen jquery-core-exercise-4 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Hide all the input elements within a form.
Next: Check/uncheck a checkbox input or radio button.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.