How can I make this fiddle work:
http://jsfiddle.net/gAHwW/
function $escape(string) {
return string.replace(/\\(\[|\]\\)/g,'\\\\$1');
}
$(function() {
$('input[type="button"]').click(function() {
alert($escape( $(this).attr('id') )); // to show you what the escape does
$('#' + $(this).attr('id')).hide(); // doesn't work
$('#' + $escape( $(this).attr('id') )).hide(); // doesn't work
$('#alsosquare[]').hide(); // doesn't work
//$(this).hide(); // works
//$('#alsosquare\\[\\]').hide(); // works
});
});
I need to select elements by their name/id dynamically, and their names/ids can have square brackets.
Thanks!
You simply have to double escape(
\\) the brackets.Here’s a demo: http://jsfiddle.net/k3YyX/
Here’s a quote from the jQuery docs:
Update:
Here’s your fiddle, in working condition: http://jsfiddle.net/gAHwW/1/
All I did was replace
'\\\\$1'with this'\\$1'in your$escapefunction.