Introduction
In this article, I will discuss how to bind a select option on drop-down using pure JavaScript. Client-side binding is faster than that of the server-side. So, I need to bind the select option or drop-down using JavaScript.
Example
To achieve my goal, I will present a demo here. In the below demo, I will bind the student names in the dropdown.
Client-side code
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BindDropDown.aspx.cs" Inherits="XMLWrite.BindDropDown" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script type="text/javascript">
- var ddlStudents;
- function GetStudentDetails() {
- ddlStudents = document.getElementById("<%=ddlStudents.ClientID %>");
- PageMethods.GetStudentDetails(OnSuccess);
- }
- window.onload = GetStudentDetails;
- function OnSuccess(response) {
- ddlStudents.options.length = 0;
- AddOption("Please select", "0");
- for (var i in response) {
- AddOption(response[i].Name, response[i].Id);
- }
- }
- function AddOption(text, value) {
- var option = document.createElement('option');
- option.value = value;
- option.innerHTML = text;
- ddlStudents.options.add(option);
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
- </asp:ScriptManager>
- <div>
- <asp:DropDownList ID="ddlStudents" runat="server">
- </asp:DropDownList>
- </div>
- </form>
- </body>
- </html>

Join the conversation! Your thoughts help the community grow.