日期:2014-05-17  浏览次数:20838 次

关于select和checkbox的关联
[size=18px][size=13px]我现在有一个select的下拉列表,表里的内容已经从数据库中读取到了,然后我想在点击下拉列表的时候,在下面生成一些checkbox,select中的集合为list1,checkbox中的集合为list2,而因为list1中的数据的一个字段在list2中数据也存在。怎么进行相对应的关联?
例如 list1中存放game 字段有id name等  然后list2中有id,name,game_id的字段  我现在都已经把两个列表的数据全读取出来了,然后怎么根据主外键的关联来做select 和checkbox 的关联啊 ??

------解决方案--------------------
可以用js写嘛,list2数据不是很多的话。checkbox都放在一个div里面,select改变的时候动态生成div的内容
------解决方案--------------------


<html>
<body onload="change()">
<div>
<select name="year" id="year" onchange="change()">
<option value="33" selected>33</option>
<option value="44">44</option>
<option value="55">55</option>

</select>
</div>
<div>
<input type="checkbox" id="33">我是33</input>
<input type="checkbox" id="44">我是44</input>
<input type="checkbox" id="55">我是55</input>
</div>
</body>
<script>
function change(){
var year=document.getElementById('year').value;
var checkbox=document.getElementById(year);
checkbox.checked="checked";
}
</script>
</html>


LZ大体的意思就是你把list1里面的id当option的value,之后checkbox的id的名字用list2的game_id定义,
当select触发onchange事件的时候,传入对应的选中值,之后去查找这个id等于值的,之后让他选中!
------解决方案--------------------
LZ,估计你的意思是list1中的id在list2中,找到对应2条记录,就选择的时候,生成2个checbox的话,这个你只能调用ajax,获取选择的select,之后去action或者servlet里面匹配list2中的,之后返回匹配记录,之后遍历这个结果,用 
var checkbox=document.createElement("input");
checkbox.type="checkbox";
checkbox.id=select选中的值
checkbox.InnerHtml=遍历集合中的 name,
至于是默认勾选就用
checkbox.checked="checked";
之后把生成的checbox添加到div或者body里面!
------解决方案--------------------
LZ,你这项目用到ajax请求了吗?用的话,我给个大概的例子,因为我这也不好去跑程序!
------解决方案--------------------


<html>
<body>
   <div>
<select name="year" id="year" onchange="schange()">
<option value="33" selected>33</option>
<option value="44">44</option>
<option value="55">55</option>

</select>
</div>
<div id="createCheckBox"></div>
<body>

</html>
<script>
function schange(){
var year=document.getElementById('year').value;
jQuery.post('xxxxx.action',{year:year},function (data) {
var createCheckBox = document.getElementById("createCheckBox") ;
var list = data.list2 ;

for(var i=0;i<list.length;i++) {
var checkbox=document.createElement("input");
checkbox.type="checkbox";
checkbox.id=list[i].game_id;
checkbox.innerText=list[i].name;
createCheckBox.appendChild(checkbox);
}
},'json');

}
</script>

下面是xxx。action的代码

JSONObject json = new JSONObject();
json.put("list2", list2);
super.response().setCharacterEncoding("UTF-8");
try {
PrintWriter printWrite = super.response().getWriter();
printWrite.write(json.toString());