4

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 !

Aakash Chakravarthy
  • 10,523
  • 18
  • 61
  • 78
  • 1
    possible duplicate of [What is the difference between these different ways to escape square brackets inside jQuery selectors](http://stackoverflow.com/questions/18573178/what-is-the-difference-between-these-different-ways-to-escape-square-brackets-in) – Rikard Sep 23 '13 at 17:54

6 Answers6

8

The following should work:

alert($('#meta\[152\]\[value\]').val());

or

var id = "#meta\[152\]\[value\]";
alert($(id).val());

Working Example

Conversion Function:

function ConvertValue(id)
{
    var test = id.replace(/[[]/g,'\\\\[');
    return "#" + test.replace(/]/g,'\\\\]'); 
}

Conversion Example

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
6

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]']")

amosrivera
  • 26,114
  • 9
  • 67
  • 76
3

The simplest way is just to use the regular getElementById, which requires no escaping:

document.getElementById("meta[152][value]").value;
Dennis
  • 32,200
  • 11
  • 64
  • 79
1

this shoudl work for you, you almost had it:

    $(document).ready(function() {
       var id = "#meta\\[152\\]\\[value\\]";
        alert($(id).val()); 
    });
Ian Jamieson
  • 4,376
  • 2
  • 35
  • 55
0

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' />
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
0

Um, just put the escaped value right in your string.

var id = "#meta\\[152\\]\\[value\\]";

See it working here

idrumgood
  • 4,904
  • 19
  • 29
  • thanks for the try.. but i just gave id = "#meta[152][value]" as an example and i cannot directly change it . It need to be changed using regex or replace – Aakash Chakravarthy Dec 06 '11 at 17:28