jquery escape square brackets to select element

本小妞迷上赌 提交于 2019-12-18 17:06:33

问题


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 !


回答1:


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




回答2:


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




回答3:


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

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



回答4:


this shoudl work for you, you almost had it:

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



回答5:


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

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

See it working here




回答6:


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


来源:https://stackoverflow.com/questions/8404037/jquery-escape-square-brackets-to-select-element

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