使用Jquery-Ajax改變Select標籤進行聯動
頁面存在著一組select標籤,它們的id分別是clientType和type。type隨著clientType的選擇而改變。
執行個體:
$('#clientType').change(function(){
var val = $('#clientType option:selected').val();//擷取當前選中的值
//根據不同情況請求不同資料
if(val == 1){
$('#type').empty();//把type清空
$.ajax({
url:"/message/template/getType?type=1",
async:true,
type:'GET',
contentType:"application/json",
dataType:"json",
success:function(data){
$.each(data,function (k,p){
$('#type').append('<option value="'+p.code+'">'+p.cname+'</option>');
});
} else {
$('#type').empty();//把type清空
$.ajax({
url:"/message/template/getType?type=2",
async:true,
type:'GET',
contentType:"application/json",
dataType:"json",
success:function(data){
$.each(data,function (k,p){
$('#type').append('<option value="'+p.code+'">'+p.cname+'</option>');
});
}
});
}
});
jquery ajax 讀取聯動菜單 select菜單
示範
JavaScript Code
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
XML/HTML Code
<div style="margin:20px">
<label>大類:</label> <select name="country" class="country">
<option selected="selected">--Select--</option>
<?php
include('../../conn.php');
$sql=mysql_query("select * from bigclass");
while($row=mysql_fetch_array($sql))
{
$id=$row['bigclassid'];
$data=$row['bigclassname'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select> <br/><br/>
<label>小類 :</label>
<select name="city" class="city">
<option selected="selected">--Select--</option>
</select>
</div>
ajax.php
PHP Code
<?php
include('conn.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select * from smallclass where bigclassid='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['smallclassid'];
$data=$row['smallclassname'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
基於JQuery的Select下拉框聯動(級聯)
這段時間在指導學生完成實訓項目,由一個用到了JQuery進行下拉框(select)聯動(添加刪除option)的操作,本來在上課中都是講過的,但時間一長都忘光了,下面把這段簡單的JS貼出來,給入門者一個DEMO吧,以後有學生不會寫的時候他能到這找到參考。
代碼要點:
1、使用JQuery給select標籤添加option元素時,直接使用:
$("篩選符").append("<option value='隱藏值'>顯示文字</option>")
2、清空select中所有元素可以使用:
$(".child").html("")
或者是
$(".child").empty()
3、擷取select標籤選擇值時用:(直調用val()方法即可)
$(".parent").val()
下面是樣本JSP頁面全文:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<title>基於JQuery的下拉框級聯操作</title>
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function changChild(tid){
$.post("childSelect",{"tid":tid},function(json){
$(".child").html("");//清空學生下拉框
for(var i=0;i<json.length;i++){
//添加一個學生
$(".child").append("<option value='"+json[i].id+"'>"+json[i].name+"</option>");
}
},'json');
}
$(function(){
//初始化教師下拉框
$.post("parentSelect",null,function(json){
for(var i=0;i<json.length;i++){
//添加一個教師
$(".parent").append("<option value='"+json[i].id+"'>"+json[i].name+"</option>");
}
changChild($(".parent").val());
},'json');
//註冊教師下拉框事件
$(".parent").change(function(){
changChild($(this).val());
});
});
</script>
</head>
<body>
<h3>使用JQuery進行下拉框的聯動</h3>
<p>
改變教師下拉框,發送AJAX請求,根據返回的JSON資料重新填充學生下拉框。
</p>
<hr/>
<select class="parent"></select>
<select class="child"></select>
</body>
</html>
服務端是用Struts的一個Action,使用Json-lib將資料轉化成json字串:(見全文)
public class SelectChangeAction {
private static List<Teacher> teachers = new ArrayList<Teacher>();
private static List<Student> students = new ArrayList<Student>();
private int tid;
static{
Teacher teacher = null;
Student student = null;
for(int i=0;i<10;i++){
teacher = new Teacher();
teacher.setId(i);
teacher.setName("教師【"+i+"】");
for(int j=0;j<10;j++){
student = new Student();
student.setId(j);
student.setName(teacher.getName()+"的學生【"+i+"|"+j+"】");
student.setTeacher(teacher);
students.add(student);
}
teachers.add(teacher);
}
}
/**
* 輸出教師資訊
* @return
*/
public String parent(){
String json = JSONArray.fromObject(teachers).toString();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 輸出學生資訊
* @return
*/
public String child(){
List<Student> list = new ArrayList<Student>();
for (Student student : students) {
if(student.getTeacher().getId() == tid){
list.add(student);
}
}
String json = JSONArray.fromObject(list).toString();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
}