js代码实现checkbox(复选框)只能选择几个。
1,弹出提示对话框模式
html代码示例:
<script language="javascript"> <!-- function affirm(t) { var ipt = document.getElementsByTagName("input"); var i = 0; var allownum = 2;//定义最多能选择的个数 for(var j = 0; j < ipt.length; j++) { if(ipt[j].type == "checkbox" && ipt[j].checked) i++; } if(i > allownum) { alert("你最多只能选择"+ allownum +"项!"); t.checked = false; } } //--> </script> <input type="checkbox" name="checkbox" value="1" onclick="affirm(this)" />1 <input type="checkbox" name="checkbox" value="2" onclick="affirm(this)" />2 <input type="checkbox" name="checkbox" value="3" onclick="affirm(this)" />3 <input type="checkbox" name="checkbox" value="4" onclick="affirm(this)" />4
2,选择几项后,其它复选框变为不可选模式。
html代码示例:
<script language="javascript"> <!-- function affirm(t,num) { var ipt = document.getElementsByTagName("input"); var i = 0; var allownum = 2;//定义最多能选择的个数 for(var j = 0; j < ipt.length; j++) { if(ipt[j].type == "checkbox" && ipt[j].checked) i++; } if(i > allownum - 1) { for(var z = 1; z <= num; z++) { if(document.getElementById("cb"+z).checked == true) { document.getElementById("cb"+z).disabled = ""; } else { document.getElementById("cb"+z).disabled = "disabled"; } } } else { for(var z = 1; z <= num; z++) { document.getElementById("cb"+z).disabled = ""; } } } //--> </script> <input type="checkbox" name="checkbox" id="cb1" value="1" onclick="affirm(this,4)" />1 <input type="checkbox" name="checkbox" id="cb2" value="2" onclick="affirm(this,4)" />2 <input type="checkbox" name="checkbox" id="cb3" value="3" onclick="affirm(this,4)" />3 <input type="checkbox" name="checkbox" id="cb4" value="4" onclick="affirm(this,4)" />4
与数据库连接关联起来
<script language="javascript"> <!-- function affirm(t,num) { var ipt = document.getElementsByTagName("input"); var i = 0; var allownum = 2;//定义最多能选择的个数 for(var j = 0; j < ipt.length; j++) { if(ipt[j].type == "checkbox" && ipt[j].checked) i++; } if(i > allownum - 1) { for(var z = 1; z <= num; z++) { if(document.getElementById("cb"+z).checked == true) { document.getElementById("cb"+z).disabled = ""; } else { document.getElementById("cb"+z).disabled = "disabled"; } } } else { for(var z = 1; z <= num; z++) { document.getElementById("cb"+z).disabled = ""; } } } //--> </script> <% set rs = server.CreateObject("adodb.recordset") sql = "select * from type" rs.open sql,conn,1,1 i = 1 num = rs.recordcount do while not rs.eof %> <input type="checkbox" name="checkbox" id="cb<%=i%>" value="<%=rs("id")%>" onclick="affirm(this,<%=num%>)" /><%=rs("value")%> <% i = i + 1 rs.movenext loop rs.close() set rs = nothing %>