Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Web =>  JavaScript

Square bracket in checkbox name

  Pi Ke      2011-03-22 10:32:40      3,224    0    0

i have a form with checkboxes like this:

    <input type=\"checkbox\" name=\"type[]\" value=\"1\" />Fast Food<br>
   
<input type=\"checkbox\" name=\"type[]\" value=\"2\" />Table Service<br>
   
<input type=\"checkbox\" name=\"type[]\" value=\"3\" />Cafeteria<br>

when i use the brackets in the name (type[]), my php works:

    $type=$_POST[\'type\'];

    echo
\"types are:\";
for ( $counter = 0; $counter < sizeof($type); $counter += 1) {
    echo
\"<br>\".$type[$counter];
}

but my javascript doesn\'t work:

    var f = document.addform;
   
for (var i=0;i<f.type.length;i++){
       
if(f.type[i].checked==true){
           
break;
       
}
       
if(i==(f.type.length-1)){
            alert
(\"No categories entered!\");
            valid
=false;
       
}
   
}

however, if i take away the brackets:

<input type=\"checkbox\" name=\"type\" value=\"1\" />Fast Food<br>

then the PHP doesn\'t work but the javascript does.

what\'s going on here? what should i use?

thanks.

link|edit|flag

PHP has an unusual system for handling multiple form controls with the same name, it expects the names to include [] but it doesn\'t use them in the variable name.

JavaScript doesn\'t have that issue. The property will still have the brackets.

Of course, square brackets have special meaning in JS, so you can\'t use dot notation to access the property.

f[\'type[]\'][i].checked
link|edit|flag
that works. thanks! – vee Jul 8 \'10 at 20:11
\"\"

In javascript, you could use f[\'type[]\'] instead of f.type. It\'s only php that changes [] to array.

link|edit|flag
that works. thanks! – vee Jul 8 \'10 at 20:11

Of course, you can also put a \'key\' in between the square brackets, too (ie. give each field an actual unique name). Something like \'type[1]\', \'type[2]\' and \'type[3]\'. PHP still throws it into an array (keyed by those numbers) and JS could access them, too.

link|edit|flag

PHP SQUARE BRACKET JAVASCRIPT ARRAY OF N

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

Hot deployment

By sonic0002