Adrian Adrian -3 years ago 163
HTML Question

How to solve the “Uncaught TypeError: Cannot read property 'checked' of null”

I have ‘n’ number of check box.
The check box displays:

<?php
$result=mysql_query("select * from tablename where status='approved'");
$result1=$count=mysql_result(mysql_query("select max(id) from tablename where status='approved'"),0);
$limit=mysql_num_rows($result);
while($row=mysql_fetch_array($result)){?>

<input type="checkbox" name="chekgrp[]" id="cheks_<?php echo $row['id'];?>" onclick="Checkchk()" value="<?php echo $row['id'];?>" />
<?php }
?>


The value n is set in a hidden field

<input type ="hidden" value="<?php echo $limit; ?>" id="hiddenval" name=" hiddenval">


The javascript validation is:

var limits=parseInt(document.form.hiddenval.value);
var countelm=0;
for(i=1;i<= limits;i++){
if (("cheks_"+i).length>0){
if(document.getElementById("cheks_"+i).checked)
{
countelm = countelm +1;
}
}
}


It shows the above error if change the status to unapproved an element from table. I know it’s because I have changed the status of certain element. Is there any other way to check if element exists (checking length doesn't help) ? How to solve this error? Please help me.

Answer Source

Try the following

  1. Use document.querySelectorAll to find all your checkboxes
  2. Array.prototype.slice to truncate the list to $limit items
  3. Array.prototype.filter to limit the list to the checked ones, and
  4. Array.prototype.length to get the count

HTML / PHP

<input type="checkbox" name="chekgrp[]" id="cheks_<?= $row['id'] ?>" onclick="Checkchk()" value="<?= $row['id'] ?>" />

JS

var limits = parseInt(document.getElementById('hiddenval').value, 10)
var selector = 'input[type="checkbox"][name="chekgrp[]"]'
var countelm = Array.prototype.slice.call(document.querySelectorAll(selector), 0, limits)
    .filter(function(checkbox) { return checkbox.checked })
    .length
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download