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

Pass an html array to javascript

P: 51
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.

Expand|Select|Wrap|Line Numbers
  1.  <script language="JavaScript">
  2. function checkAll(field)
  3. {
  4.     for (i = 0; i < field.length; i++)
  5.         field[i].checked = true ;
  6. }
  7. function uncheckAll(field)
  8. {
  9.     for (i = 0; i < field.length; i++)
  10.         field[i].checked = false ;
  11. }
  12. function handle_button(field)
  13. {
  14.     for(i = 0;i < field.length; i++)
  15.         if(field[i].checked == false)
  16.         {
  17.             checkAll(field);
  18.             return;
  19.         }
  20.     uncheckAll(field);
  21. }
  22.  
  23. </script>
Then in the HTML

Expand|Select|Wrap|Line Numbers
  1. Value 1:
  2. <input name="values[]" value="tsa" type="checkbox">
  3. <br>
  4. Value 2: <input name="values[]" value="ts" type="checkbox">
  5. <br>
  6. Value 3: <input name="values[]" value="s" type="checkbox">
  7. <br>
  8. <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.
Jul 13 '08 #1
Share this Question
Share on Google+
5 Replies


100+
P: 210
It doesn't work. Can anybody tell me what's wong with it?
i is the problem. Think about it.
Jul 14 '08 #2

P: 51
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.
Jul 17 '08 #3

acoder
Expert Mod 15k+
P: 16,027
Use document.getElementsByName("value[]") or document.forms["input"].elements["value[]"]
Jul 17 '08 #4

hsriat
Expert 100+
P: 1,654
I should say, you can solve your problem by cutting down your JavaScript to 3 lines.

Expand|Select|Wrap|Line Numbers
  1. funtion checkUncheck(masterCheck) {
  2.     var chks = document.getElementsByName('value[]');
  3.     for (var i in chks)
  4.     chks[i].checked = masterCheck.checked;
  5. }
[html]<input type="checkbox" onclick="checkUncheck(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.
Jul 17 '08 #5

P: 51
Thanks for the help guys!
Jul 17 '08 #6

Post your reply

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