I struggle to use a jquery selector containing brakcets.
Basically I parse a JSON response from the server in my jquery code. Then I iterate over the object, once the parsing is done.
This object has such a structure:
errors = {
input#title_id: "error message",
select#authors_id[]: "error message 2"
}
Then I iterate over this map like follow:
$.each(errors, function(fieldSelector,errMsg){
fieldSelector = fieldSelector.replace('[','\\\\[');
fieldSelector = fieldSelector.replace(']','\\\\]');
$(fieldSelector).hide(); //for the example
}
Everything works well except for the select that has an id with brackets!
Per the jQuery Selector documentation, you need to use two brackets to escape meta-characters:
But the double brackets are only required so that a single bracket char
\is present in the selector string. The selector engine then uses that bracket later on to escape the meta character. Anyway, this means that your code also only needs to use two brackets – there is no need to provide an extra level of escaping: