0

Ok, say I have checkboxes like so:

<input type="checkbox" name="class[]" value="name 1">
<input type="checkbox" name="class[]" value="name 2">
<input type="checkbox" name="class[]" value="name 3">

How can I make the following script work:

<script type="text/javascript">
checkboxlimit(document.forms.morning.class[], 2)
</script>

If I leave the [] within the javascript, it becomes a syntax error. Is there a way of having those brackets in there or should that JS line be written another way?

1 Answers1

0

You can change it to:

checkboxlimit(document.forms.morning["class[]"], 2)

Edit: Fiddle

Ballbin
  • 717
  • 6
  • 12
  • The brackets in javascript (and most languages) are reserved characters. I would avoid using them for naming if possible. – Ballbin May 09 '14 at 17:36
  • this didn't seem to work, I still get a syntax error? – ACanadianCoder May 09 '14 at 17:39
  • 1
    Using brackets for form element names is common practice when working with PHP in the backend. See http://www.php.net/manual/en/faq.html.php#faq.html.arrays. – Felix Kling May 09 '14 at 17:50
  • @ACanadianCoder: What is the error message? Personally I advice to use `document.getElementsByName('class[]')`. – Felix Kling May 09 '14 at 17:50
  • Is it the same error you were seeing before? I added my fiddle in the answer. – Ballbin May 09 '14 at 17:52
  • @FelixKling The backend is a Perl script. But if I put those brackets in the JS portion, the script doesn't work anymore – ACanadianCoder May 09 '14 at 18:32
  • @acan: yep, but bracket notation fixes that. I'm not sure about Perl, maybe you don't need brackets in the name in that case. "Doesn't work" is not a useful error description btw. – Felix Kling May 09 '14 at 18:34
  • @FelixKling lol sorry. If I do the whole document.getElementsByName('classs[]') it doesn't give me an error anymore but the script that limits it to only 3 choices doesn't seem to work anymore. I can keep selecting more than 3 that I want. document.getElementsByName.classs would work but I need to grab the multiple values for the name="class" class. – ACanadianCoder May 09 '14 at 18:45
  • @acan: I don't see a reason why it shouldn't work, but since I don't know what the script does, there is not much I can help you with. – Felix Kling May 09 '14 at 18:47
  • @FelixKling It's ok, I will try to find another way. Thanks for your input. – ACanadianCoder May 09 '14 at 18:50