Checkboxes, JavaScript and PHPYou may already know that if you name a set of checkboxes as an array, that array can be passed directly into PHP. This is especially useful where the form itself is created from data on-the-fly using PHP. For example:
<FORM ACTION='action.php' METHOD='post'>
<INPUT TYPE='checkbox' NAME='delStory[]' VALUE='4574'>
<INPUT TYPE='checkbox' NAME='delStory[]' VALUE='4577'>
<INPUT TYPE='checkbox' NAME='delStory[]' VALUE='4581'>
<INPUT TYPE='checkbox' NAME='delStory[]' VALUE='4602'>
<INPUT TYPE='submit' ONCLICK='return checkDel(this.form);'>
</FORM>
If all these boxes were checked, action.php would receive a string array in $_POST['delStory'] containing '4574,4577,4581,4602'. However, if you need some client-side form validation, JavaScript will have problems since you cannot directly use square brackets in referring to the form elements. Instead you have to go an indirect route, creating a JavaScript object first - thus:
<SCRIPT TYPE='text/javascript' LANGUAGE='JavaScript'>
function checkDel(form) {
var temp=form.elements['delStory[]'];
var flag=0;
if (temp.length > 0) {
for (i=0;i < temp.length;i++) {
if (temp[i].checked) flag++;
}
}
if (flag > 0) {
if (!confirm('Delete - are you sure ?')) return false;
return true;
} else {
alert('NOTE: None of the boxes were checked');
return false;
}
}
</SCRIPT>
The problem comes where there is only one checkbox in the form. In this case, you will find that the length of the array is returned as 'undefined'. I have yet to find a way around this...
Technorati tags: JavaScript PHP form array validation