View Single Post
Old 01-16-2013, 02:37 PM   PM User | #2
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Try this:-

Code:
<form id="world" action = "">

USA <input type="checkbox" name="countries[]" value="USA" onclick="chkChecks('countries[]')">
Canada<input type="checkbox" name="countries[]" value="Canada" onclick="chkChecks('countries[]')">
Japan <input type="checkbox" name="countries[]" value="Japan" onclick="chkChecks('countries[]')">
UK <input type="checkbox" name="countries[]" value="UK" onclick="chkChecks('countries[]')">
China <input type="checkbox" name="countries[]" value="China" onclick="chkChecks('countries[]')">
France <input type="checkbox" name="countries[]" value="France" onclick="chkChecks('countries[]')">
<br>
<input type = "button" value = "Show choices" onclick = "showchoices('countries[]')"> 

</form>

<script type="text/javascript">

function chkChecks(nme) {
var isChecked = 0;
var c = document.getElementsByName(nme);
for (var i = 0; i < c.length; i++) {
if (c[i].checked) {
isChecked ++;

if (isChecked >2) {  // maximum of two checkboxes - change as required
alert ('You may only select a maximum of two checkboxes');
c[i].checked = false;
return false;
}
}
}
}

function showchoices(nme) {
var checkedVals = "";
var report = "You have not selected any boxes!" 
var c = document.getElementsByName(nme);
for (var i = 0; i < c.length; i++) {
if (c[i].checked) {
checkedVals += c[i].value + " ";
}
}

if (checkedVals != "") {report = "You have selected " + checkedVals}
alert (report);
}

</script>
Quizmaster: Castel Gandolfo is the summer residence of which religious leader?
Contestant: Jesus
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 01-16-2013 at 03:06 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
blati (01-16-2013)