retrive two values in separate textboxes from database using dropdown onchange event jsp without using table index

时间:2018-07-24 10:23:32

标签: javascript mysql scriptlet

Following code will show only one value in a text box but what i need is if i select one drop down option it has to display all it's row values in each separate text boxes..retrive two or more values in separate textboxes from database using dropdown onchange event jsp without using table index.

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@page import = "java.sql.*" %>
        <%@page import = "java.sql.DriverManager.*" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <script type="text/javascript">
    function populateCustomerId(){
        var selectBox = document.getElementById('selectBox');
         var selectedCustomerId = selectBox.options[selectBox.selectedIndex].value;
        document.getElementById('customerId').value = selectedCustomerId;

    }</script>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Select</title>
    </head>
    <body>
    <%
    try{   
        Class.forName("com.mysql.jdbc.Driver");
        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/ravi","root","root");
        Statement st = con.createStatement();
        ResultSet rs = null;
            rs = st.executeQuery("select rid, rname, rmbl from r"); 
    %>
        <select id="selectBox" onchange="populateCustomerId();">
            <%while(rs.next()){ %>

                <option value="<%=rs.getString(2) %>"><%=rs.getString(1) %></option>

            <%} %>
            <%}
        catch (Exception e){
                e.printStackTrace();
            } %>

        </select>
        <input id="customerId" type="text" value="" />
        <input id="" type="text" value="" />
        <input id="" type="text" value="" />
    </td>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

简单地将数据传递到元素的data属性,如下所示

<option value="<%=rs.getString(2) %>" data-name="<%=rs.getString(3)%>" data-xyz="value-which-you-want-to-get-in-change-event"><%=rs.getString(1) %></option>

现在您可以在更改事件函数中获取该值

function populateCustomerId(){
        var selectBox = document.getElementById('selectBox');
         var selectedCustomerId = selectBox.options[selectBox.selectedIndex].value;

        var xyz = selectBox.options[selectBox.selectedIndex].getAttribute('data-xyz');
        var name = selectBox.options[selectBox.selectedIndex].getAttribute('data-name');

        document.getElementById('customerId').value = selectedCustomerId;
        document.getElementById('customerName').value = name;
        document.getElementById('customerXyz').value = xyz;

    }

这只是一个简单的示例,您可以执行此操作。 您可以根据需要进行改进。