Reputation: 402
I know there are already a lot of posts in SO regarding this issue. But none of them works for my case.
I've multiple select inputs with the following naming format:
select name="violationCategory[${theCount.count-1}].subCategory"
which translates to something like:
select name="violationCategory[0].subCategory"
select name="violationCategory[1].subCategory"
.. so on
I've to apply a particular class on these select inputs if some condition is fulfilled. So, I try replacing the square brackets with something like this:
if(key.indexOf("[") >= 0){
key = $.trim(key).replace("name=^[","name=^\\[");
key = $.trim(key).replace("].","\\].");
alert(key);
$("#" + formId + " select[name=" + key + "]").addClass('inputBoxError');
}
The alert prints:
violationCategory[1\].subCategory]
and I get the error:
Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1\].subCategory]
When I change the code to:
key = $.trim(key).replace("].","\].");
alert prints:
violationCategory[1].subCategory]
and I get the error:
Uncaught Error: Syntax error, unrecognized expression: #referralViolationForm select[name=violationCategory[1].subCategory]
So, basically it works neither ways.
Can anyone help me out as to how to escape the square brackets.
Upvotes: 1
Views: 3465
Reputation: 388316
Your attribute value should be wrapped within ""
, there is no need to escape the [
or ]
$('#' + formId + ' input[name="' + key + '"]').addClass('inputBoxError');
So the translated selector should be
$('#myform input[name="violationCategory[1].subCategory"]').addClass('inputBoxError');
Update
You need to select a <select>
element, then you need to change the element selector input
to select
like $('#' + formId + ' select[name="' + key + '"]').addClass('inputBoxError');
Upvotes: 4
Reputation: 4320
Special characters need to be escaped by \
. Which needs to be escaped as well, so - here's an example to deal with your case: http://jsfiddle.net/tb2cW/1/
And here's the list of characters in need of escaping: ~!@$%^&*()_+-=,./\';:"?><[]{}|
and `
Upvotes: 1