I have a form with several ingredients on it. I want a user to be able to select 3 and no more than 3. So if they ticked 3 then the form wouldn’t allow any more but they could untick a choice and pick another.
At the moment though it doesn’t stop a box from being ticked and doesn’t count an untick.
My javascript
<script type="text/javascript">
var total = 0;
function check() {
if( $("input#name").checked = true )
{
total = total + 1;
}
if( $("input#name").checked = false )
{
total = total - 1;
}
if(total > 3)
{
alert("Please Select only three")
$("input#name").checked = false ;
return false;
}
}
</script>
and my form
<form name="ingredientlist" method="post" action="checkboxdone.php">
<label>Pork</label><input type="checkbox" name="ckb" value="pork" onclick="check();"/><br/>
<label>Carrot</label><input type="checkbox" name="ckb" value="carrot" onclick="check();"/><br/>
<label>Whiskey</label><input type="checkbox" name="ckb" value="whiksey" onclick="check();"/><br/>
<label>Bacon</label><input type="checkbox" name="ckb" value="bacon" onclick="check();"/><br/>
<label>Leek</label><input type="checkbox" name="ckb" value="leek" onclick="check();"/><br/>
<label>Potato</label><input type="checkbox" name="ckb" value="potato" onclick="check();"/><br/>
<input id="button" type="submit" value="Submit" name="button"/>
</form>
Plug this into your code and it will run just dandy.
http://jsfiddle.net/W9gNg/1/