Tuesday, December 30, 2008

[jQuery] Re: Posting multiple values from a checkbox

 

From: Karl Swedberg
Sent: Tuesday, December 30, 2008 7:42 PM
To: jquery-en@googlegroups.com
Subject: [jQuery] Re: Posting multiple values from a checkbox

On Dec 30, 2008, at 8:11 PM, Michael Geary wrote:


Your checkboxes all have the same ID attribute, and they have no NAME
attribute. Give each one a unique ID and NAME. You can use same value for
those two attributes in a single checkbox, or they can be different. But
each ID and each NAME should be unique.

Hey Mike,

Is it necessary to give each one a unique name? I've read this a number of times, but I've also read the contrary, and PHP seems to like the array-like naming convention for checkboxes:

 <input type="checkbox" id="apples" name="food[]" value="apples" />
 <label for="apples">Apples</label>

 <input type="checkbox" id="pizza" name="food[]" value="pizza" />
 <label for="pizza">Pizza</label>

 <input type="checkbox" id="cake" name="food[]" value="cake" />
 <label for="cake">Cake</label>

So, if I check the Apples checkbox and the Pizza checkbox, the $_Post array will look like this:

Array
(
    [food] => Array
        (
            [0] => apples
            [1] => pizza
        )
)

It's pretty handy, but if there is a compelling argument against doing that, I'm willing to be persuaded. 
 
Ah, good point, Karl. I don't know of any reason not to do that. I didn't mean to imply that the unique names was the only way to do it. It's just the approach I'm most familiar with! :-) 

You may run into an alternate syntax for using the <label> tags, where you
don't use the for="..." but instead nest the <input> tag inside the <label>.
That is cleaner, but it doesn't work in IE so it's best avoided. Use the
for="..." instead.

There is nothing wrong with doing both -- nesting the <input> inside the <label> and using the "for" attribute. Or is there?
 
Nope, nothing wrong at all with nesting the tags and using the "for" attribute. I used the non-nested tags just for simplicity, since you do need the "for" attribute for IE. I wonder if there would be any advantage to nesting the tags? Maybe it's more semantic?
 
-Mike

No comments: