Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I use brackets in the name attribute of input element? [duplicate]

Tags:

html

Possible Duplicate:
Using square brackets in hidden HTML input fields

What can I do with brackets in the name attribute of input element? This is tutorial:

<input id="user_email" name="user[email]" size="30" tabindex="1" type="text">
like image 703
uzay95 Avatar asked Oct 30 '11 17:10

uzay95


2 Answers

They have no particular meaning in HTML. Some server-side frameworks, including PHP, use that sort of notation as an indication that they should build up the data in a single server-side object (an associative array in PHP's case). So with PHP, for instance, if you had name="user[email]" and name="user[phone]" and submitted the form, in your PHP code on the server you'd retrieve a single user object from the request and it would have the keys email and phone on it. Or if you had name="tags[]" on multiple inputs, PHP would build an array with all of the values called tags on the request object.

like image 112
T.J. Crowder Avatar answered Oct 15 '22 16:10

T.J. Crowder


As far as HTML is concerned, they are just characters you can use in the name, no different from a, 7 or !.

If you plan to access form elements via the name on the client side, then they prevent you using dot notation to do so in JavaScript (since [ has special meaning in JS) so you have to use square bracket notation instead.

You might treat the characters as having special significance once they reach the server. PHP which will file the data as $_REQUEST['user']['email'] instead of $_REQUEST['user[email]'], and a number of other form parsing libraries for various languages have adopted the feature.

like image 4
Quentin Avatar answered Oct 15 '22 16:10

Quentin