js select级联,上面分类,下面是内容
js select级联,上面分类,下面是内容。
js级联效果如下:
html和js代码如下:
<html>
<head>
<title>js select级联,上面分类,下面是内容</title>
<meta http-equiv="Content-Type" content="text/html;charset=GBK"/>
</head>
<body>
<div>
<label for="form-field-select-1">分类:</label>
<select class="form-control" onchange="changeType(this)">
<option value="">请选择</option>
<option value="1">水果</option>
<option value="2">蔬菜</option>
<option value="3">其他</option>
</select>
</div>
<div>
<label for="form-field-select-1">内容:</label>
<select id="itemId" class="form-control" multiple="multiple">
</select>
</div>
<script type="text/javascript">
var waItemsJson = [
{"type_id":1,"id":11,"item_code":"苹果","item_name":"苹果"},
{"type_id":1,"id":11,"item_code":"香蕉","item_name":"香蕉"},
{"type_id":1,"id":11,"item_code":"梨","item_name":"梨"},
{"type_id":2,"id":11,"item_code":"白菜","item_name":"白菜"},
{"type_id":2,"id":11,"item_code":"青菜","item_name":"青菜"},
{"type_id":3,"id":11,"item_code":"可乐","item_name":"可乐"}
];
function changeType(obj){
removeAll("itemId");
for(var i=0;i<waItemsJson.length;i++){
if(obj.value==waItemsJson[i].type_id || obj.value=="" ){
addOption("itemId",waItemsJson[i].item_name,waItemsJson[i].item_name);
}
}
}
/**
* 删除objId下所有的options
*/
function removeAll(objId){
var obj=document.getElementById(objId);
obj.options.length=0;
}
/**
* objId下 添加 option
*/
function addOption(objId,text,value){
var obj=document.getElementById(objId);
obj.options.add(new Option(text,value)); //这个兼容IE与firefox
}
</script>
</body>
</html>