javascript - 在 jsp 中选择 <option> 从数据库中获取值

标签 javascript html mysql jsp

我正在开发一个基于 Web 的应用程序,其中有一个列表和一个相关的文本框。我在列表中添加了客户名称。当我在列表中选择客户名称时,我希望在文本框中填写客户 ID。我曾尝试使用 javascript 函数,但这只能帮助我了解客户名称。

客户 ID 不是选项标签的值,它是我在注册客户时输入的客户代码。所以我想从mysql数据库中获取客户代码。

有人可以给我一些建议吗? 这是我的 jsp 代码。

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

             Statement st = null;
             ResultSet rs = null;

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

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


      <%  } %>

最佳答案

Priyanka Pawar,您需要在语句查询中获取客户 ID,如下所示:

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

    Statement st = null;
    ResultSet rs = null;

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

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

Javascript:

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; 
}

关于javascript - 在 jsp 中选择 <option> 从数据库中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561568/

相关文章:

html - CSS - 选中选择时显示 div

php - 如何在特定日期自动从 MySQL 数据库中删除行?

javascript - AJAX 脚本不加载 "see"元素

javascript - 如何为字符串中所有相同的 URL 定义相同的数字?

html - C# 中的自动缩进

javascript - jQuery scrollTop 不滚动到最后一个 child

php - 特定查询语法在 php mysqli 中无效,但在 MySQL CLI 中无效。

mysql - 在 MYSQL 中触发删除

javascript - 在 Javascript 中重新创建 Processing map 函数

javascript - 选择具有以特定值开始/结束的 id 属性的元素