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 !

Answers:

Answer

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

Answer

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

Answer

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

document.getElementById("meta[152][value]").value;
Answer

this shoudl work for you, you almost had it:

    $(document).ready(function() {
       var id = "#meta\\[152\\]\\[value\\]";
        alert($(id).val()); 
    });
Answer

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

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

See it working here

Answer

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' />

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.