How To get selected value of dropdownlist using javascript in asp.net


ASP.NET provides server-side control Dropdownlist, but this works only server-side means when we change the item, the data post back to the server, and then it returns to the client-side. We want to achieve the same thing but on the client-side using JavaScript.In this quick post, I will show you how to achieve this. Check out the following code snippet; it’s clean and clear, and easy to understand.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DiffrentColour.aspx.cs" Inherits="DiffrentColour" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
   <style type="text/css">
       .blue { background-color: #ADD8E6; color: #000000; }
       .red { background-color: #E20A0A; color: #ffffff; }
       .green { background-color: #3CB371; color: #ffffff; }
       .yellow { background-color: #FFF280; color: #000000; }
   </style>

   <script type="text/javascript">
       function Change()
       {
        var e = document.getElementById("ddlColor"); // select element
        var strColor = e.options[e.selectedIndex].value; //select value
        e.options[e.selectedIndex].className=strColor; //change class
     
       }
 
   </script>

</head>
<body >
   <form id="form1" runat="server">
       <asp:Panel ID="pnl" runat="Server" GroupingText="Dropdownlist">
           <div>
               <asp:DropDownList ID="ddlColor" runat="Server" onchange="Change();">
                   <asp:ListItem Value="red">Red</asp:ListItem>
                   <asp:ListItem Value="blue">Blue</asp:ListItem>
                   <asp:ListItem Value="green">Green</asp:ListItem>
                   <asp:ListItem Value="yellow">Yellow</asp:ListItem>
               </asp:DropDownList>
           </div>
       </asp:Panel>
   </form>
</body>
</html>

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم