I'm trying to target some dynamic form variables using jquery. Only problem is that they contain square brackets (they're array format) and I can't seem to get the regex to work that would correctly find and then replace the string with the correct formatting for jquery.
Demo code :
<div id="test[array][1]">wibble</div>
<div id="test[array][2]">wibble</div>
<div id="test[array][3]">WIBBLE</div>
<div id="test[array][4]">WIBBLE</div>
<button onclick="clicky();">test</button>
<script>
function clicky() {
//1 fail
$("#test[array][1]").html("moo");
//2 works
element = "#test\\[array\\]\\[2\\]";
console.log(element);
$(element).html("moo");
//3 fail
element = "#test[array][3]";
element.replace(/\[/g, "\\[");
element.replace(/\[/g, "\\]");
$(element).html("moo");
console.log(element);
//4 fail
element = "#test[array][4]";
element.replace(/\[.*?\]/g,'\\$1');
console.log(element);
$(element).html("moo");
};
</script>
Array[2] is working but I need to be able to convert a randomly generated string into a version thats acceptable for jQuery. It also confuses me as console.log shows the element with only 1 backslash.
Im passing in a string eg '#test[array][1]' and need to get that into a format which jQuery will accept as an identifier.
Any pointers would be greatly appreciated!
[id='test[array][1]']instead