Reputation: 10691
Consider a input element
<input id="meta[152][value]" type="text" />
Here the input field is dynamically generated. I need to select that field. So I used,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
So how to do that ? I currently use this code,
var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as
/** I need the value of id to be escaped using regex,replace or any other method to get #meta\[152\]\[value\] and not manually **/
alert($(id).val());
Your suggestions will be helpful !
Upvotes: 4
Views: 15359
Reputation: 17388
You can use the _.escapeRegExp
method from the Lodash library.
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />
Upvotes: 0
Reputation: 76547
The following should work:
alert($('#meta\[152\]\[value\]').val());
or
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Conversion Function:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\\\[');
return "#" + test.replace(/]/g,'\\\\]');
}
Upvotes: 8
Reputation: 32598
The simplest way is just to use the regular getElementById, which requires no escaping:
document.getElementById("meta[152][value]").value;
Upvotes: 3
Reputation: 4816
this shoudl work for you, you almost had it:
$(document).ready(function() {
var id = "#meta\\[152\\]\\[value\\]";
alert($(id).val());
});
Upvotes: 1
Reputation: 26514
If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")
Upvotes: 6
Reputation: 4924
Um, just put the escaped value right in your string.
var id = "#meta\\[152\\]\\[value\\]";
Upvotes: 0