Does anyone know how to escape the square bracket character when setting a class name with jQuery?
Try the following:
$(\'#txtFirstname\').addClass(\
Short answer: you don't need to escape brackets because the argument is a class name, not a selector. It didn't work for you because of a bug in earlier jQuery versions that has long been fixed.
To demonstrate it, here's your code running under different versions:
$('#txtFirstname').addClass('test[someval]')
$('#txtFirstname').attr('class')
console.log($('#txtFirstname').hasClass('test[someval]'));
$('#txtFirstname').addClass('test[someval]')
$('#txtFirstname').attr('class')
console.log($('#txtFirstname').hasClass('test[someval]'));
So the issued was apparently fixed on jQuery/1.4.0. I found a ticket regarding this (though it's tagged as being fixed on 1.4.2 rather than 1.4.0).
I insist: the rule to quote or escape metacharacters with \\ in order to use them as a literal part of a name only applies to selectors. However, the .hasClass() method does not receive a selector as argument but as class name:
.hasClass( className ) className Type: String The class name to search for.