您的位置:首页 > 数据库

Js实现select联动,option从数据库中读取

2015-11-25 18:52 330 查看
待要实现的功能:页面有两个select下拉列表,从第一个select中选择后,在第二个select中出现对应的列表选择,再从第二个select中选择后,在一个text中显示对应的信息。两个select和text的数据全部来自oracle数据库,该功能用js实现。

首先我们先定义两个select和text:

<select id="department" style="width: 80px" onChange="selectChange(this.value)">
  <option value=''>-请选择-</option>
</select>


这个是第一个select,用来选择员工所在的部门,其中注意后面那个onChange方法。这个就是当你选择了一个选项后,调用函数selectChange(),这个函数是在js里用来实现联动第二个select的。

<select id="empl" style="width: 100px" onChange="showName(this.value)">
<option value=''>-请选择-</option>
</select>


这个是第二个select用来选择员工,在onChange方法中的函数也是在js中自己定义的用来实现在text中显示相应信息的函数。

<input type="text" name="emplInfo" value="这里显示员工信息" size="15" maxlength="50">


在数据库中有下表:

create table department(
dept_no   varchar2(4),
dept_name varchar2(20)
)

create table empl_Info(
empl_no   varchar2(8),
empl_name varchar2(10),
dept_no    varchar2(4),
empl_text  varchar2(50)
)


简单定义了一个,第一张表是部门表,在第一个select中显示,第二个表是员工信息表,在第二个select中显示,然后在text中显示empl_text中的信息。

下面是js中的实现:

array = new Array();
<%
int count = 0;
rs=stmt.executeQuery("select e.empl_no, e.empl_name, e.dept_no, e.empl_text from department d, empl_Info e where d.dept_no=e.dept_no order by e.dept_no desc");
String deptno = "";
String emplno = "";
  String emplname = "";
  String empltext = "";
while(rs.next()){
deptno = rs.getString("dept_no");
emplno = rs.getString("empl_no");
emplname = rs.getString("empl_name");
empltext = rs.getString("empl_text");
%>
array[<%=count%>] = new Array("<%=emplno%>","<%=emplname%>","<%=deptno%>","<%=empltext%>");
<%count++;
}
%>


这一步根据需要可以调整,为了举例方便,这是在页面加载时完成的,所以如果数据很多,加载速度有些慢。之后我们要取的数据就可以从array中读取了。

function init(){
document.getElementByIdx_x("department").length = 1;
<%
rs=stmt.executeQuery("select * from department order by dept_no desc");
String dno="";
String dname="";
while(rs.next()){
dno= rs.getString(1);
    dname= rs.getString(2);%>
document.getElementByIdx_x("department").options[document.getElementByIdx_x("department").length] = new Option("<%=dno%> <%=dname%>");
document.getElementByIdx_x("department").options[document.getElementByIdx_x("department").length-1].value="<%=dno%>";
<%}%>
}
function selectChange(id){
document.getElementByIdx_x("empl").length = 1;
for(var i = 0;i<array.length;i++){
if(array[i][2] == id){
document.getElementByIdx_x("empl").options[document.getElementByIdx_x("empl").length] = new Option(array[i][0]+ " "+array[i][1]);
document.getElementByIdx_x("empl").options[document.getElementByIdx_x("empl").length-1].value=array[i][0];
}
}
}

function showName(id){
document.getElementByIdx_x("emplInfo").value = array[id-1][1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: