jquery escape square brackets to select element

女生的网名这么多〃 提交于 2019-11-30 15:38:28

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

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

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

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

this shoudl work for you, you almost had it:

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

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

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

See it working here

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' />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!