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 !


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


如果你感觉更舒适而不逃避,你也可以使用属性选择器并使用这个id来搜索元素,如下所示: $("[id='meta[152][value]']")


最简单的方法就是使用常规的getElementById,它不需要转义:

document.getElementById("meta[152][value]").value;
链接地址: http://www.djcxy.com/p/87988.html

上一篇: JQUERY:未捕获错误:语法错误,无法识别的表达式

下一篇: jquery转义方括号来选择元素