471,895 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,895 software developers and data experts.

Check Box Problem

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
2 1241
8,658 Expert Mod 8TB
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
2,476 2GB
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.

Similar topics

8 posts views Thread by pw | last post: by
6 posts views Thread by Shannan Casteel via AccessMonster.com | last post: by
1 post views Thread by scprosportsman | last post: by
6 posts views Thread by tommaso.gastaldi | last post: by
12 posts views Thread by tshad | last post: by
2 posts views Thread by Ben | last post: by
reply views Thread by YellowAndGreen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.