CrazyEngineers
  • How to Populate DropDown Menu by selecting another DropDown Menu

    TheV

    Member

    Updated: Oct 26, 2024
    Views: 3.6K
    Hey friends ,
    I want to populate the dropdown menu on selecting another dropdown menu. I try javascript but I couldn't do it. What I want to do is there is two dropdown menu, semester and subject. On selecting semester I should get all the subjects of that semester in my subject dropdown menu. Technology: Javascript, jsp, servlet, html
    Please help...!
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • deepu11111111

    MemberApr 7, 2012

    I am trying
    Are you sure? This action cannot be undone.
    Cancel
  • Manish Goyal

    MemberApr 7, 2012

    This is very simple job
    You just have to use ajax for doing this or if you want to do this in Javascript only then you can do this

    Add a onChange Event on Semester drop down

    and check for ID of semester and append new Options to subjects drop down accordingly
    Are you sure? This action cannot be undone.
    Cancel
  • TheV

    MemberApr 7, 2012

    I don't know Ajax at all... 😔 Is there is any nice site to learn from..?
    Are you sure? This action cannot be undone.
    Cancel
  • Manish Goyal

    MemberApr 8, 2012

    Above code will help you in implementing it, there might be some syntax error in this code , as i have not checked it, use firebug in mozilla for checking it
    Now Coming to explanation of its working

    1:- Now whenever you will select semester
    Jquery will capture onChange event and fire ajax to the server and will fetch corresponding subject for the that semester and returns the response
    Jquery will then parse that response in success function and fill the corresponding Subject Combo Box
    I hope you got an Idea , what i am saying , if you still need details explanation, then take help from google
    Just use following query
    Populate combo-box box dynamically on Change
    You will get thousands of search results
    Are you sure? This action cannot be undone.
    Cancel
  • sookie

    MemberApr 8, 2012

    Please check below example how it can be done through JavaScript. In order to get the values for Subjects drop down, you will have to hit the server once or either you can load them during page load itself as I have saved them by "comma separator".
    <html>
    <head>
    <script type="text/javascript">
    function populateDropDown(){
     
    /* Clear the entire subjects drop down*/
    document.getElementById("subjectsList").options.length = 0;
     
    /* adding a Default "Select" option in Subjects Menu*/
    var optn = document.createElement("OPTION");
    optn.text = "Select";
    subjectsList.options.add(optn);
     
    /* This can be changed according to the rest of the code instead of hard coded values*/
    var selectedIndexVal = document.getElementById("semestersList").selectedIndex;
    var subjectValList =document.getElementById("semestersList").options[selectedIndexVal].value;
    var subjectValArray=subjectValList.split(",");
    for(var j=0;j<subjectValArray.length;j++){
    var optn = document.createElement("OPTION");
    optn.text = subjectValArray[j];
    optn.value = subjectValArray[j];
    subjectsList.options.add(optn);
    }
     
    }
    </script>
    </head>
    <title>Drop Down Test</title>
    <body>
    Drop Down 1:&nbsp;<select id="semestersList" onchange="javascript:populateDropDown(this);">
    <option value="">Select</option>
      <option value="Subject1,Subject2,Subject3">Semester 1</option>
      <option value="Subject4,Subject5,Subject6">Semester 2</option>
      <option value="Subject7,Subject8,Subject9">Semester 3</option>
      <option value="Subject10,Subject11">Semester 4</option>
        <option value="Subject12">Semester 5</option>
      <option value="Subject13,Subject14,Subject15,Subject16">Semester 6</option>
      <option value="Subject18">Semester 7</option>
      <option value="Subject19">Semester 8</option>
    </select>
    <br/><br/>
    Drop Down 2:&nbsp;<select id="subjectsList"><option value="">Select</option>
    </select>
    </body>
    </html>
    Let me know if you want to go with Ajax approach.
    Are you sure? This action cannot be undone.
    Cancel
  • TheV

    MemberApr 9, 2012

    Actually I wanna do in this way...!!
    <SCRIPT TYPE="text/javascript">
    function PopulateSubjectMenu(){
            alert("I wannt populate Dropdown menu dynamically");
     
            var ss = document.getElementById("sem_select").value;
            var dt = document.getElementById("dept_select").value;
            <%
            int semx = 6; // Here I wanna assign ss
              String deptx = "cse"; // Here I wanna assign dt
     
                Connection c = ConnectDB.createConn();
                Statement s = c.createStatement();
                ResultSet rx = s.executeQuery("Select sub_code,sub_name from subject_details where semester ="+ semx +" and department='"+ deptx +"'");
     
            while(rx.next()){ %>
            var sub_select = document.getElementById("sub_select");
            var optn = document.createElement("OPTION");
            optn.text = <%=rx.getString(2)%>;
            optn.value = <%=rx.getString(1)%>;
            sub_select.options.add(optn);
          <% }%>
        }
    </SCRIPT>
    
    I want to fetch the values from the database and then assign it to the sub_select (dropdown menu). And the HTML codes are below..: ---
    <HTML>
    <BODY>
    <FORM>
    Semester :
            <label>
            <select name="sem_select" id="sem_select" onchange="">
              <option value="null">-- Select --</option>
              <option value="1">First</option>
              <option value="2">Second</option>
              <option value="3">Third</option>
              <option value="4">Fourth</option>
              <option value="5">Fiveth</option>
              <option value="6">Sixth</option>
              <option value="7">Seven</option>
              <option value="8">Eight</option>
            </select>
            </label>
        
    <select name="dept_select" id="dept_select" onchange="PopulateSubjectMenu();">
              <option value="null">-- Select --</option>
              <option value="cse">Computer Science & Engineering</option>
              <option value="ec">Electronics & Communication</option>
              <option value="it">Information Technology</option>
              <option value="ft">Food Technology</option>
              <option value="ee">Electrical Engineering</option>
              <option value="ei">Electronics & Intrumentation</option>
            </select>
    <select name="sub_select" id="sub_select">
              <option value="null">--Select--</option>
     
            </select>
    </FORM>
    </BODY>
    </HTML>
    Are you sure? This action cannot be undone.
    Cancel
  • TheV

    MemberApr 9, 2012

    I am trying to do in this way but I am not even getting the alert massage .....
    Are you sure? This action cannot be undone.
    Cancel
  • sookie

    MemberApr 9, 2012

    TheV
    I am trying to do in this way but I am not even getting the alert massage .....
    I will correct your code[javascript method : PopulateSubjectMenu()] later but till that time check the JavaScript error in Fire-bug console or IE browser.As far as I know you cannot use JSP scriptlets in JavaScript until or unless it is expression.

    You will have to hit the DB using Ajax on change of drop down.
    Are you sure? This action cannot be undone.
    Cancel
  • TheV

    MemberApr 9, 2012

    sookie
    I will correct your code[javascript method : PopulateSubjectMenu()] later but till that time check the JavaScript error in Fire-bug console or IE browser.As far as I know you cannot use JSP scriptlets in JavaScript until or unless it is expression.

    You will have to hit the DB using Ajax on change of drop down.
    [INFO] 2012-04-10 11:10:58:840: coupons: warning: strange fullLink=undefined
    [INFO] 2012-04-10 11:10:58:840: coupons: warning: strange fullLink=undefined
    [INFO] 2012-04-10 11:10:58:840: coupons: warning: strange fullLink=undefined
    [INFO] 2012-04-10 11:10:58:840: coupons: warning: strange fullLink=undefined

    I am getting the above warning...!!
    So Ajax is the last option left . . !
    Are you sure? This action cannot be undone.
    Cancel
  • sookie

    MemberApr 9, 2012

    Nope you will get this error, the one I already told you cannot use "scriptlets" in JavaScript
    [​IMG]
    Are you sure? This action cannot be undone.
    Cancel
  • TheV

    MemberApr 9, 2012

    Ohh...! I think varies from browser to browser..!!
    So I have to do using AJAX only..!
    Are you sure? This action cannot be undone.
    Cancel
  • sookie

    MemberApr 9, 2012

    Here is your modified code

    <SCRIPT TYPE="text/javascript">
     
    /* Function called on change event of Dept Drop Down */   
    function populateSubjectMenu() {
     
        var selectedIndexVal = document.getElementById("sem_select").selectedIndex;
        var selectedSemVal =document.getElementById("sem_select").options[selectedIndexVal].value;
     
        selectedIndexVal = document.getElementById("dept_select").selectedIndex;
        var selectedDeptVal =document.getElementById("dept_select").options[selectedIndexVal].value;
        callAjaxFunction(selectedSemVal,selectedDeptVal);
       
      }
     
    /* function called to do Ajax Request */
      function callAjaxFunction(semVal,deptVal){
      var url="populateSubjects.jsp?semVal="+semVal+"&"+deptVal;
     
        var xmlHttp;
            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
     
            var xmlHttp = new XMLHttpRequest();
     
          } else if (window.ActiveXObject) { // IE
     
            var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
     
        xmlHttp.open('POST', url, true);
        xmlHttp.onreadystatechange = function() {
     
            if (xmlHttp.readyState == 4) {
     
                updatepage(xmlHttp.responseText);
            }
     
        }
    xmlHttp.send(url);
      }
     
    /* Call back function of Ajax Response*/
    function updatepage(response){
    //alert(str);
    document.getElementById("result").innerHTML = response;
    }
    </SCRIPT>
    <HTML>
    <BODY>
    <FORM>
    Semester :
            <label>
            <select name="sem_select" id="sem_select" >
              <option value="">-- Select --</option>
              <option value="1">First</option>
              <option value="2">Second</option>
              <option value="3">Third</option>
              <option value="4">Fourth</option>
              <option value="5">Fiveth</option>
              <option value="6">Sixth</option>
              <option value="7">Seven</option>
              <option value="8">Eight</option>
            </select>
            </label>
    
    Department :
    <select name="dept_select" id="dept_select" onchange="populateSubjectMenu();">
              <option value="">-- Select --</option>
              <option value="cse">Computer Science & Engineering</option>
              <option value="ec">Electronics & Communication</option>
              <option value="it">Information Technology</option>
              <option value="ft">Food Technology</option>
              <option value="ee">Electrical Engineering</option>
              <option value="ei">Electronics & Intrumentation</option>
    </select>
    
    <div id="result"></div>
    </FORM>
    </BODY>
    </HTML>
    Here is the code for "populateSubjects.jsp" which acts as servlet on ajax call
    <%@page import="java.sql.*"%>
    <%@page import="javax.sql.*"%>
    <%
                //open a database connection
                Connection conn = null;
                PreparedStatement stmt = null;
                ResultSet rs = null;
                try{
     
                  String url = "jdbc:sqlserver://[DB Server IP]:[DB Server Port];";
                  String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                  String userName = "[Your Schema username]";
                  String password =  [Your Schema pwd] ;
                  String semVal=request.getParameter("semVal");
                  String deptVal=request.getParameter("deptVal");
               
                  Class.forName(driver).newInstance();
                  conn = DriverManager.getConnection(url,userName,password);
               
                  String s=[FONT=Consolas]"Select sub_code,sub_name from subject_details where semester ="+ [/FONT] semVal [FONT=Consolas]+" and department='"+ [/FONT] deptVal [FONT=Consolas]+"'"[/FONT];
                  stmt=conn.prepareStatement(s);
                  rs=stmt.executeQuery();
               
                  out.print("<p class='style9'>Subjects : ");
                  out.print("<select name='sub_select' id='sub_select'>");
                  out.print("<option value=''>--Select--</option>");
                   
                  while (rs.next()) {
                  String  [SIZE=13px][FONT=Consolas]sub_code[/FONT][/SIZE]= rs.getString("[SIZE=13px][FONT=Consolas]sub_code[/FONT][/SIZE]");
                  String  [SIZE=13px][FONT=Consolas]sub_name[/FONT][/SIZE] = rs.getString("[SIZE=13px][FONT=Consolas]sub_name[/FONT][/SIZE]");
                  out.print("<option value='"+[SIZE=13px][FONT=Consolas]sub_code[/FONT][/SIZE]+"'>"+[SIZE=13px][FONT=Consolas]sub_name[/FONT][/SIZE]+"</option>");           
                  }
                  out.print("</select>");
                 
                 
                }catch(Exception e ){
                    out.print("<div><font color='red'>The following exception was thrown:</font></div>");
                }finally{
                    try{if(rs!=null)rs.close();}catch(SQLException e2){/*noop*/}
                    try{if(stmt!=null)stmt.close();}catch(SQLException e2){/*noop*/}
                    try{if(conn!=null)conn.close();}catch(SQLException e2){/*noop*/}
                }
    %>
    In order to run the above files, Please deploy them in any web container or app server and change the DB connection details to that of yours. Let me know if any issues.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register