...

View Full Version : error with script



squarefish
12-14-2006, 12:31 PM
Hi there

Firstly let me state that I am a bit of a noob when it comes to javascript!

I have written this script which lets a user check 3 of the 4 boxes then if they click the 4th it tells them they can only select 3 then removes the check from the last one they checked.

It seems quite an ugly expensive bit of code and I was wondering if there was a simpler way of doing it. (there may end up being 20/30 checkboxes)

If not can anyone shed any light on the error I am getting even thoughtthe script executes correctly.

document.form1.car.4.value is null or not an object ??

Thanks
Richard



<html>
<head>
<script language="javascript">
<!--
function checkboxes(field) {
var total = 0;
var max = form1.car.length;
for (var idx = 0; idx < max; idx++) {
if (eval("document.form1.car[" + idx + "].checked") == true) {
total += 1;
if (total > 3) {
alert("You can only select 3 vehicles.");
for (var idy = 0; idx < max; idy++) {
if (eval("document.form1.car[" + idy + "].value") == field) {
document.form1.car[idy].checked = false
}
}
}
}
}
}

-->
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<input name="car" type="checkbox" value="1" onclick="checkboxes(this.value)"/>
<input name="car" type="checkbox" value="2" onclick="checkboxes(this.value)"/>
<input name="car" type="checkbox" value="3" onclick="checkboxes(this.value)"/>
<input name="car" type="checkbox" value="4" onclick="checkboxes(this.value)"/>
</form>
</body>
</html>

Arty Effem
12-14-2006, 04:26 PM
for (var idy = 0; idx < max; idy++)
Look very carefully at what you've done there.

Your use of eval is totally unnecessary.

Always try to make functions as re-usable as possible, by not hard-coding object names into them. This modification could be used on any set of checkboxes:

function checkBoxLimit(limit,field)
{
var checkBoxGroup=field.form[field.name];
var max = checkBoxGroup.length;

for (var idx = 0, total=0; idx < max; idx++)
{
if( checkBoxGroup[idx].checked )
{
total += 1;
if (total > limit)
{
alert("You can select only "+limit);
for (var idy = 0; idy < max; idy++)
if (checkBoxGroup[ idy ].value == field.value)
checkBoxGroup[ idy ].checked = false
}
}
}
}

.
.
onclick="checkBoxLimit(3,this)"



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum