Ahmad Labib Mansour February 2016

Dynamically change JSP page content without buttons

I've written a code that dynamically fills a drop down list from an SQL database. Next, I need to change the content of the page depending on user selection in real-time (no buttons), perhaps show another label, or even show another drop down list that also gets it's values from an SQL DB depending on the previous selection etc.. Here is my code

<%@ page import="java.sql.*" %>
<%ResultSet resultset = null;
Connection conn;%>
<HTML>
<%
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-O708F3G\\SQLEXPRESS;databaseName=master",
                "user", "pswd");

        Statement statement = conn.createStatement();

        resultset = statement.executeQuery("select * from RTable");
%>
<h1> Drop down list</h1>
    <select name="projectname">
        <%  while (resultset.next()) {%>
        <option><%= resultset.getString(2)%></option>
        <% } %>
    </select>
<%
    } catch (Exception e) {
        out.println("error"+e);
    }
%>
</HTML>

After all the selections are done, I will display a "submit" button that sends the selected data to a back-end servlet (I know how to do that once the button is there).

Answers


Sachin Kumar February 2016

You can write the following javascript function and call it on the onchange event of your <select> element:

    <p id="demo"></p>

    <script>
    function myFunction() {
        var x = document.getElementById("mySelect").value;
        document.getElementById("demo").innerHTML = "You selected: " + x;
    }
    </script>
//Your JSP Code
    <select name="projectname" id="mySelect" onchange="myFunction()">
        <%  while (resultset.next()) {%>
        <option value="<%= resultset.getString(2)%>"><%= resultset.getString(2)%></option>
        <% } %>
    </select>

Please check the code for the value attribute of your <option>, it might be wrong; but the other code will work fine. I have added the 'id' and 'onchange' attributes for the <select> tag.

Post Status

Asked in February 2016
Viewed 3,849 times
Voted 8
Answered 1 times

Search




Leave an answer