Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation for checkboxes

Tags:

javascript

Hello
I have a JS function which says

for(var i = 0; i < document.calDailyBlock.selFilCheckBox.length; i++)  
{  
  if(document.calDailyBlock.selFilCheckBox[i].checked)  
  {  
     filteredInitId += document.calDailyBlock.selFilCheckBox[i].value + ",";  
     alert(filteredInitId);  
     isProjCheck = true;  
  }  
}  
document.calDailyBlock.filteredComId.value = filteredInitId;  

When there are no checkboxes on the page and I try to click on Filter button which calls this function, I receive an error "document.calDailyBlock.selFilCheckBox.length' is null or not an object"

Is there any simple thing which I can add in this function ?

Also can anyone help me how to check if there is only one checkbox on one page ?

Thanks in advance

like image 324
Priyanka Avatar asked May 29 '26 22:05

Priyanka


1 Answers

I think you are relying on a fairly obscure (non-official) feature of some browsers which lets you get an element from the document as if it were an attribute. In other words, you are going:

document.calDailyBlock

This is searching the document for a variable calDailyBlock. Instead, you should use the standardised getElementById:

document.getElementById("calDailyBlock")

And use the same approach for getting selFilCheckBox.

This will return null if calDailyBlock or selFilCheckBox are not found. Before you go calling length on them (which gives that error), you should check to see if you got back null, and then (I suppose) fail silently (don't do anything).

like image 150
mgiuca Avatar answered Jun 01 '26 11:06

mgiuca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!