Fields in CakePHP could not be referred by JQuery
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']开发者_Python百科" 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,
because this is the naming convention in CakePHP.
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 withname="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.
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?
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.
精彩评论