tags:

views:

44

answers:

3

Hi all,

I have got a simple HTMl form with one field as follows:

<input type="text" name="data['User']['user_id']" id="data['User']['user_id']" value="1"> 


$(document).ready(function(){
$("#data['User']['user_id']").mouseover(function(){
alert("hello");
});

});

The code couldn't work,

I think it may be the name of the Input text field that caused the problem,
but I don't know how to alter it

because this is the naming convention in CakePHP.

A: 

I believe that

$("#data[User][user_id]")

is telling jQuery to look for the element with

id="data[User][user_id]"

, not

name="data[User][user_id]"

Not sure though, someone correct me?

W_P
A: 

The problem is that JQuery is pretty dumb about matching things that have brackets in the matching text. Use the following as your selector:

 $("[id^=data['User']['user_id']]")

It uses the ^= comparison operator for "starts with", which seems to work for me.

Hober
Say I got another Input text field named like thisname="data['User']['username']"The old code you suggested: $("[name^=data['User']['user_id']]")will raise another problemWhen I moved my mouse over the second field, the alert popped up too.
+2  A: 

The jQuery documentation has the answer:

If you wish to use any of the meta-characters (#;&,.+*~':"!^$[]()=>|/) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an an input with name="names[]", you can use the selector $("input[name=names\\[\\]]").

So in your case: $("input[name=\\[User\\]\\[user_id\\]]")

Note though that I think the HTML snippet you posted is bogus. By default the Cake form helper creates elements like this:

<input type="text" name="data[User][user_id]" id="UserUserId" value="1"> 

The name does not contain any ' and the id is camelCased to be easily selectable.

deceze
Oh yes you are right, deceze.I have made a big mistake in my question.It should be name="data[User][user_id]"Thank you so much for help.