views:

44

answers:

4

Im currently writing some form validation with jQuery and having the followin problem..

I give ids to my inputs in such a way that when data is posted, i have an array to work with like so..

<input type="text" id="user[name]" />
<input type="text" id="user[email]" />

This means that when the data is posted to my script, i will have a "user" arrau available so i can do things like $user["name"]however, when i try to select the inputs with jquery by doing..var name = $("#user[name]") it wont work. But if i just have the id of the input as "username" then var name = $("#username") will work.

Im assuming its to do with CSS selectors in jquery as it things im trying to access a user object with an ID of name? like the way $("input[username]") would select an input with the id of username.

Any ideas on how i can get around this? And would it work in all browsers?

+1  A: 

The id value of a form element is not what gets passed to the server, it is only used internally by the document DOM and scripting languages. It is the name that gets passed.

Your form elements need to be altered to something like this:

<input type="text" id="username" name="user[name]" />
<input type="text" id="useremail" name="user[email]" />

The HTML 4 specification addresses the proper naming of elements:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Using square brackets in the name attribute is a common technique to pass data in an array format to the server side scripting language, but using them in an id will certainly confuse JQuery.

zombat
ahh, thats it, Thanks!
cast01
A: 

I'm not completely surprised that the selector doesn't work, because your IDs are not valid according to the HTML specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

The PHP manual has a tutorial on the correct way to pass form elements as an array to the server, using the name attribute rather than the ID:

<input name="MyArray[keyOne]" />
<input name="MyArray[keyTwo]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
Dexter
A: 

Try one of these:

$("[id='user[name]']")
$("#user\\[name\\]")
$("#user\\005Bname\\005D")
Gumbo
A: 

First of all know that the name attribute is what gets posted and not the id.

Now to the issue

to access <input type="text" id="user[name]" /> with jQuery you need to do it like this

var name = $("input[id='user[name]']");
Gaby