tags:

views:

801

answers:

1

Hello

Does anyone know how to escape the square bracket character in jQuery?

Try the following:

$('#txtFirstname').addClass('test[someval]')

then

$('#txtFirstname').attr('class')

you'll see the class is there.

Now try

$('#txtFirstname').hasClass('test[someval]')

FAIL

The only reason I can think of is the square brackets.

And I need these for my jQuery validation you see.

Any suggestions appreciated

Cheers Duncan

+3  A: 

And lo, he searched for 12 hours for the answer, gave up and posted a question on SO, then within 2 seconds found the answer.

I'll put it here for other less fortunate souls.

Escape with TWO (2) backslashes.

http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_that_has_weird_characters_in_its_ID.3F

Duncan
Congratulations!
peirix
Happens to me many times.
RichN
The two backslashes are only because of JavaScript string escaping. It's actually, correctly, a single backslash you are sending to jQuery itself.
bobince
Didn't know that, thanks.
Duncan