Priyanka Pawar Priyanka Pawar - 6 months ago 18
HTML Question

fetch value from database on selection of <option> in jsp

I am developing one web based application where I have one list and one dependent textbox. I have added customer names in list. I want customer id to be filled in textbox when I will select customer name in list. I have tried using javascript function but that only helps me to know customer name.

Customer Id is not value of option tag its customer code which I have entered while registration of customer. So I want to fetch customer code from mysql database.

Can any one please suggest me something?
This is my jsp code.

<% DBConnection dbc=new DBConnection();
Connection con=dbc.getNewConnection();

Statement st = null;
ResultSet rs = null;

st=con.createStatement() ;
rs=st.executeQuery("select cname from CustomerMaster");
<select id="selectBox" >

<% while({ %>
<option ><%= rs.getString(1)%></option>

<% } %>


Priyanka Pawar, you need to fetch customer-id in statement query as following:

    DBConnection dbc = new DBConnection();
    Connection con = dbc.getNewConnection();

    Statement st = null;
    ResultSet rs = null;

        st = con.createStatement();
        /* You need to get customerId here, suppose your cid is customerId from table */
        rs = st.executeQuery("select cid, cname from CustomerMaster"); 

    <!-- Changing dropdown value will call javascript method populateCustomerId() -->
    <select id="selectBox" onchange="populateCustomerId();">
        <%while({ %>
            <!-- rs.getString(1) would be your customerId set as option value -->
            <option value="<%=rs.getString(1) %>"><%=rs.getString(2) %></option>
        <%} %>
    <input id="customerId" type="text" value="" />


function populateCustomerId(){
    var selectBox = document.getElementById('selectBox');

    /* selected value of dropdown */
    var selectedCustomerId = selectBox.options[selectBox.selectedIndex].value;

    /* selected value set to input field */
    document.getElementById('customerId').value = selectedCustomerId;