我正在开发一个基于 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/