Pass an html array to javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Muffinthief
    New Member
    • May 2007
    • 51

    Pass an html array to javascript

    Hi guys, what I'm trying to do is very simple. Just make a simple check/uncheck button for some checkboxes. Here's what I have.

    Code:
     <script language="JavaScript">
    function checkAll(field)
    {
    	for (i = 0; i < field.length; i++)
    		field[i].checked = true ;
    }
    function uncheckAll(field)
    {
    	for (i = 0; i < field.length; i++)
    		field[i].checked = false ;
    }
    function handle_button(field)
    {
    	for(i = 0;i < field.length; i++)
    		if(field[i].checked == false)
    		{
    			checkAll(field);
    			return;
    		}
    	uncheckAll(field);
    }
    
    </script>
    Then in the HTML

    Code:
    Value 1:
    <input name="values[]" value="tsa" type="checkbox">
    <br>
    Value 2: <input name="values[]" value="ts" type="checkbox">
    <br>
    Value 3: <input name="values[]" value="s" type="checkbox">
    <br>
    <input name="CheckAll" value="(Un)Check All" onclick="handle_button(document.input.values[])" type="button">
    It doesn't work. Can anybody tell me what's wong with it?
    Thanks.
  • Logician
    New Member
    • Feb 2007
    • 210

    #2
    Originally posted by Muffinthief
    It doesn't work. Can anybody tell me what's wong with it?
    i is the problem. Think about it.

    Comment

    • Muffinthief
      New Member
      • May 2007
      • 51

      #3
      oops left of the var... wow. But that wasn't the problem. The problem is with "values[]" when I take off the brackets everything works. But I need the brackets for PHP down the road.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Use document.getEle mentsByName("va lue[]") or document.forms["input"].elements["value[]"]

        Comment

        • hsriat
          Recognized Expert Top Contributor
          • Jan 2008
          • 1653

          #5
          I should say, you can solve your problem by cutting down your JavaScript to 3 lines.

          [code=javascript]funtion checkUncheck(ma sterCheck) {
          var chks = document.getEle mentsByName('va lue[]');
          for (var i in chks)
          chks[i].checked = masterCheck.che cked;
          }[/code]

          [html]<input type="checkbox" onclick="checkU ncheck(this)">& nbsp;Check/Unckeck all[/html]

          If you want to use the same function somewhere else too, then provide a second argument to the function which would tell the name of the checkboxes to be (un)checked.

          Comment

          • Muffinthief
            New Member
            • May 2007
            • 51

            #6
            Thanks for the help guys!

            Comment

            Working...