jquery escape square brackets to select element

前端 未结 6 1352
余生分开走
余生分开走 2021-01-03 04:55

Consider a input element


Here the input field is dynamically generat

相关标签:
6条回答
  • 2021-01-03 05:25

    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

    0 讨论(0)
  • 2021-01-03 05:37

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

    0 讨论(0)
  • 2021-01-03 05:43

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

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

    See it working here

    0 讨论(0)
  • 2021-01-03 05:46

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

    0 讨论(0)
  • 2021-01-03 05:47

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

    document.getElementById("meta[152][value]").value;
    
    0 讨论(0)
  • 2021-01-03 05:49

    this shoudl work for you, you almost had it:

        $(document).ready(function() {
           var id = "#meta\\[152\\]\\[value\\]";
            alert($(id).val()); 
        });
    
    0 讨论(0)
提交回复
热议问题