1

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!

1
  • 1
    It would be interesting to see what effect it has on the performance, but you could use the selector [id='test[array][1]'] instead Commented Jan 3, 2013 at 14:52

2 Answers 2

1

You can still use the old document.getElementById function and then convert it to a jQuery element if needed.

Sample:

$('#clicky').click(function() {    
var element = document.getElementById("test[array][1]");
$(element).html('moo');    
});   ​

<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 id="clicky">test</button>

​Fiddler: http://jsfiddle.net/tatzz/2/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that does the trick. +1 for avoiding regular expressions too!
yep, ignore the framework and revert back to 'good old' javascript
0

You could try this to do your string replacement...

element = "#test[array][3]";
element = element.replace(/\[/g, "\\\\[");
element = element.replace(/\]/g, "\\\\]");
$(element).html("moo");  
console.log(element);

You need to assign the result of the replace back to the variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.