...

View Full Version : JavaScript button with limit



dlbhome
11-29-2012, 03:02 PM
ne1 help me add a limit of 3 to this function?

var i;
var cRecs;
cRecs = "";
for (i = 0; i < document.forms[0].length; i++){
if (document.forms[0].elements[i].type == "checkbox"){
if (document.forms[0].elements[i].checked==true){
cRecs = cRecs + document.forms[0].elements[i].name;
if (i < document.forms[0].length){
cRecs = cRecs + ",";
}
}
}
}
if (cRecs == ""){
alert("No records have been selected!");
} else {
window.open("rpt.asp?recs=" + cRecs, "Report");
}
}

Thanks in advance

Philip M
11-29-2012, 04:48 PM
Use this example.


<form id = "myform">
<input name = "myname" type = "checkbox" value = "Red" onclick="count()"> RED <br>
<input name = "myname" type = "checkbox" value = "Blue" onclick="count()"> BLUE <br>
<input name = "myname" type = "checkbox" value = "Green" onclick = "count()"> GREEN <br>
<input name = "myname" type = "checkbox" value = "Yellow" onclick = "count()"> YELLOW<br>
<input name = "myname" type = "checkbox" value = "Purple" onclick = "count()"> PURPLE<br>
<input name = "myname" type = "checkbox" value = "Grey" onclick = "count()"> GREY<br>

<br>
<br>
You have checked <input type = "text" name= "totChecked" id = "totChecked" size = "2" value = "0" readonly> checkboxes
</form>

<script type = "text/javascript">
function count() {
var f = document.getElementById("myform");
var len = f.myname.length;
var totBoxes = 0;
for (i = 0; i < len; i++) {
if (f.myname[i].checked) {
totBoxes ++;
}
if (totBoxes >3) {
alert ("You may only check a maximum of 3 boxes");
f.myname[i].checked = false;
totBoxes --;
}
}
f.totChecked.value = totBoxes;
}

</script>


Quizmaster: How many days will there be in the year 2013?
Contestant: Er... is it 60 or 52?

felgall
11-29-2012, 07:43 PM
For an example of the modern way to do this that doesn't have the JavaScript jumbled together with the HTML see http://www.felgall.com/jstip141.htm



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum