Wednesday, December 4, 2024

6 ways to get the selected text from html drop down list in jQuery?

One of the common task in web development is retrieving the selected text from a drop down list, which is nothing but HTML select element. This allows users to choose one of the options presented, each text is enclosed in option tag. how can we retrieve the selected text using jQuery? Well, there are multiple ways but core is first find the select element than the selected option by using :selected pseudo class selector. 

Here are couple of ways to do it, here listOfBooks is the Id of HTML SELECT element enclosing all options.


1. $("#listOfBooks option:selected").text();


2. $("#listOfBooks :selected").text();


3. $("#listOfBooks").children(":selected").text();


4. $("#listOfBooks").find(":selected").text();


5. $("#listOfBooks option").is("selected").text() 


6. $("#listOfBooks").children("option").is("selected").text() 


Example

<html>


<head>


<title>How to find current URL and hash using jQuery</title>

</head>


<body>


<h2>jQuery example to find the current URL and hash</h2>


<select id="listOfBooks">

<option value="">Best books to learn jQuery ....</option>

<option value="1">Head First jQuery </option>

<option value="2">Learning jQuery</option>

<option value="3">jQuery in Action</option>

</select>


<div id="board"></div>


<script src="//code.jquery.com/jquery-1.6.2.min.js"></script>

<script>

$(document).ready(function(){


$("#listOfBooks").click(function(){

var selectedText = $("#listOfBooks option:selected").text();


$("#board").html("<h3>selected text: " + selectedText + "</h3>"); 

}); 


});


</script>


</body>

</html>




That's all about how to get the selected text from drop down list using jQuery.


    No comments:

    Post a Comment