Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery escape square brackets to select element

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 !

like image 637
Aakash Chakravarthy Avatar asked Dec 03 '22 00:12

Aakash Chakravarthy


1 Answers

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

like image 82
Rion Williams Avatar answered Dec 04 '22 14:12

Rion Williams