Check Box Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • divyakgowda
    New Member
    • Oct 2007
    • 19

    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,

    Code:
    	var total=""
    		for(var i=0; i < document.formname.field_id.length; i++)
    		{
    			if(document.formname.field_id[i].checked)
    			   total +=document.formname.field_id[i].value + "\n"
    		}
    			
    	   if(total=="")
    		{
    			alert("Please select one data") 
    			return false; 
    		}
    Last edited by Dormilich; Apr 6 '09, 12:34 PM. Reason: added [code] tags
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    I think that's because you get the field by "document.formn ame.field_id", which in this case returns a HTMLInputElemen t (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 getElementsByNa me() which always returns a node-set.

    Comment

    • dmjpro
      Top Contributor
      • Jan 2007
      • 2476

      #3
      I think your CheckBox has the same name then you better to do ...

      Code:
      var check_boxes = document.getElementsByName("checkbox_name");
      for(var i=0;i<check_boxes.length;i++){
       var checkbox_ref = check_boxes[i];
       //do whatever you want to do with the reference
      }
      Actually document.formNa me.elementName. length does not work when the element is single ;)

      Comment

      Working...