开发者

PHP/Javascript limiting amount of checkboxes

Im trying to limit the amount of checkboxes that can be checked, in this case only 3 can be checked. When using plain HTML this works fine. The code can be seen below.

HTML example

<td ><input type=checkbox name=ckb value=2 onclick='chkcontrol()';></td><td>Perl</td>

Javascript Function

<script type="text/javascript">  
function chkcontrol(j) {  
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){  
total =total +1;}  
if(total > 3){  
alert("Please Select only three")       
document.form1.ckb[j].checked = false;  开发者_开发知识库
return false;
}  
}    
}  
</script>

The problem appears when replacing the fixed HTML values with values from a MYSQL database. All the information appears correctly, and can be posted to another page via a submit button. However, it seems like the 'value' assigned to each record from the database is not making its way too the javascript function.

<td><input name="checkbox[]" type="checkbox" value="<?php echo $rows['TCA_QID'];?>" onclick="chkcontrol();"></td>

I have tried changed the name in the javascript function to match the 'checkbox' name.Any advice would be greatly appreciated

Thanks


In the second version, your input element's name is "checkbox[]", but in your JavaScript function you're looking for an element with a name of ckb. The JavaScript function cannot find your field if you're telling it to look for the wrong name.

You say you've tried changing this. What happened when you tried that? Make sure you're naming the element "ckb", not "ckb[]".

Have you looked at what the checkboxes' values are in the generated HTML for the page? Do they match what you expect?


<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0

//maximum number of allowed checked boxes
var maxChecks=3

function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>

</head>

<body>
<form>
Option1 <input type="checkbox" id="check1" onclick="setChecks(this)"><br />
Option2 <input type="checkbox" id="check2" onclick="setChecks(this)"><br />
Option3 <input type="checkbox" id="check3" onclick="setChecks(this)"><br />
Option4 <input type="checkbox" id="check4" onclick="setChecks(this)"><br />
Option5 <input type="checkbox" id="check5" onclick="setChecks(this)"><br />
Option6 <input type="checkbox" id="check6" onclick="setChecks(this)"><br />

</form>
</body> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜