-2

Trying to make the infamous checkall checkbox for dynamically created rows from a MySQL query. Rows (and therefore checkboxes) could range from 1 row to a metric buttload.

The form (without the checkall) is as follows:

<form name="form" method="post" action = "process.order.php">

<?php
while($fetch = mysql_fetch_array($order_query){

$order_id = $fetch['oid'];
$order_status = $fetch['ostat'];

?>

   <input type="checkbox" name="order_row[<?=$order_id?>]" id="1" value="1">
   <select name="status[<?=$order_id?>]" id="status[<?=$order_id?>]"
   <option value="Ordered">Ordered</option>
   <option value="Backordered">Backordered</option>
   </select>
<? } ?>


<input type="submit" name="submit" id="submit" value="submit"> </form>

In process.order.php:

<?php
if(is_array($order_row)){
foreach($order_row as $order_id=>$val){

...followed by the rest of the script. I tried using this: How to implement "select all" check box in HTML? and this: Select All Checkbox

I'm trying to avoid using jQuery at this moment. Is there a way I can call the checkbox name generated by the PHP script into the javascript code?

Update: I'd like to use a function that I can call across multiple pages. Thus, calling embedding the form name in the JS won't be practical for me. Also, I'd like it to be a checkbox - the button's worked great, but I'm trying to keep the UI simple and I already have a lot of buttons I'm trying to get rid of...

Community
  • 1
  • 1
thebarless
  • 470
  • 1
  • 12
  • 34

2 Answers2

5

Working Example

You can do like this:

var frm = document.forms['form'];
for (var i = 0, l = frm.elements.length; i < l; i++) {
   if (frm.elements[i].type === 'checkbox') {
      frm.elements[i].checked = true;
   }
}

Similarly, to uncheck all set:

frm.elements[i].checked = true;

to false.

You can also easily create checkAll and unCheckAll functions using above code.


By the way, an id with only numeric value is invalid, you should use alpha or mix of alpha and numeric characters.

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 2
    In HTML5 IDs can be numeric. _The id global attribute is now allowed to have any value, as long as it is unique, is not the empty string, and does not contain space characters._ – j08691 Jun 15 '12 at 16:50
  • 1
    @j08691: yup i know, mentioned because question isn't tagged html5 – Sarfraz Jun 15 '12 at 16:52
0

If you don't have to support IE6 or 7, the following will work.

Live Demo

var checkAll = document.getElementById("checkall");

checkAll.onclick = function(){
    [].forEach.call(
        document.forms['form'].querySelectorAll("input[type='checkbox']"),
        function(el){
            el.checked=true;
    });
}

​ ​

Loktar
  • 34,764
  • 7
  • 90
  • 104