By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,503 Members | 1,143 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,503 IT Pros & Developers. It's quick & easy.

Check Box Problem

P: 19
Hello all,
My problem,i have written a javascript to check whether the checkboxes are checked or not.If its not checked,i will get an alert message,if i checked then say it is checked.This condition is working for more than one data.If there is only one data and if i check that also,i am gettin an alert message and says its not checked.Please help me to solve this.

Javascript am using is,

Expand|Select|Wrap|Line Numbers
  1.     var total=""
  2.         for(var i=0; i < document.formname.field_id.length; i++)
  3.         {
  4.             if(document.formname.field_id[i].checked)
  5.                total +=document.formname.field_id[i].value + "\n"
  6.         }
  8.        if(total=="")
  9.         {
  10.             alert("Please select one data") 
  11.             return false; 
  12.         }
Apr 6 '09 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,639
I think that's because you get the field by "document.formname.field_id", which in this case returns a HTMLInputElement (an element node, that doesn't have the length property) instead of a HTMLCollection (several elements with the same name - an element node-set).

to overcome this use the DOM method getElementsByName() which always returns a node-set.
Apr 6 '09 #2

P: 2,476
I think your CheckBox has the same name then you better to do ...

Expand|Select|Wrap|Line Numbers
  1. var check_boxes = document.getElementsByName("checkbox_name");
  2. for(var i=0;i<check_boxes.length;i++){
  3.  var checkbox_ref = check_boxes[i];
  4.  //do whatever you want to do with the reference
  5. }
Actually document.formName.elementName.length does not work when the element is single ;)
Apr 6 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.