Ralph Freshour wrote on 14 Dec 2003 at Sun, 14 Dec 2003 16:00:11
GMT:
[color=blue]
> I have multiple checkbox's created with an array name because I
> have many on the same web page - their names are like:
>
> frm_chk_delete[0]
> frm_chk_delete[1]
> frm_chk_delete[2]
> frm_chk_delete[3]
> etc.
>
> Here is my code line that creates each checkbox (the php
> variable get incremented of course):
>
> <INPUT TYPE="checkbox" NAME="frm_chk_delete[<?php echo
> $php_delete_counter;?>]">Delete
>
> When I click on the Delete button I want to call a JS routine to
> check that at least one checknbox has been checked and marked
> for deletion when the form submit is called my php file will
> detect and delete the checkboxes accordingly.
>
> I'd like to use JS before the submit and make sure at least one
> of the checkboxes is checked - how do I loop through these array
> name checkboxes in javascript to check their states before
> submitting?[/color]
It would be easier if they all had the same name, but it can be done
as it is.
<FORM ... onsubmit="return checkBoxes(this)">
function checkBoxes(form) {
var numControls = form.elements.length;
var checks = 0;
// Check every control in the form
for (var i = 0; i < numControls; ++i) {
var element = form.elements[i];
// If the name begins, frm_chk_delete[ ...
if ('frm_chk_delete[' == element.name.substr(0, 15)) {
// ...see if it's checked, and increment counter if it is
if (element.checked) checks++;
}
}
// If none of boxes have been checked, alert the user and cancel
// the submission
if (!checks) {
window.alert('Please check at least one box before submitting');
return false;
}
// If code reaches here, at least one box was checked, so allow
// the form to submit
return true;
}
If it's not guaranteed that only checkboxes will have names that
start with 'frm_chk_delete[', you should also check to make sure that
the element being inspected is a checkbox (use element.type ==
'checkbox').
Hope that helps,
Mike
--
Michael Winter
M.Winter@blueyonder.co.invalid (replace ".invalid" with ".uk")