Thursday, 19 August 2021

How to get selected text of dropdown list using jQuery ?

 Hi guys , in this post we will see how to get selected text of dropdown list using jQuery. So,let's start

In this demo, we will add one dropdown list with some value and one button control. So, on click of button , our application will show dropdown list selected text in alert.


get selected text of dropdown list using jQuery

Please follow below steps:-

1)Open you editor.

2)Add basic html tags such as html, head, script, body tag.

3)Add CDN link for jquery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

4)Add dropdown list with some values and one button control.

 <select Id="ddlName">

   <option value="0">-Select-</option>

   <option value="1">John Doe</option>

   <option value="2">Sam Sharma</option>

   <option value="3">Yogesh Verma</option>

   <option value="4">Sagar Shinde</option>

   <option value="5">Arun Dev</option>

   </select>

   <button id="btnSave">Submit</button>

5)Add following jquery code in script section:-

<script type="text/javascript">

        // Add document ready function to check DOM is fully loaded.

$(document).ready(function(){

                      // Add button click event handler

$('#btnSave').click(function(){

if($('#ddlName').val()>0){

alert($('#ddlName option:selected').text());

}

});

});

</script>

So, to get selected text of dropdown list use :-

    $('#ddlName option:selected').text()


Full Code:-

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

$('#btnSave').click(function(){

if($('#ddlName').val()>0){

alert($('#ddlName option:selected').text());

}

});

});

</script>

</head>

<body>

   <select Id="ddlName">

   <option value="0">-Select-</option>

   <option value="1">John Doe</option>

   <option value="2">Sam Sharma</option>

   <option value="3">Yogesh Verma</option>

   <option value="4">Sagar Shinde</option>

   <option value="5">Arun Dev</option>

   </select>

   <button id="btnSave">Submit</button>

</body>

</html>

Screenshot of code:-

get selected text of dropdown list using jQuery


No comments:

Post a Comment