简体   繁体   中英

Escape square brackets in jQuery selector

Currently I have the following <select> box:

<select name="selectemail[]" multiple="true">
    <option value="email">test@email.com</option>
    <option value="name">Joe</option>
    <option value="date">2015</option>
</select>

In a Javascript file I have the following:

$("#add").click(function(){ 
    /* Note the square brackets below */
    $("[name=selectemail[]] option:selected").each(function(){
        $("#text").val($("#text").val() + $(this).text() + "\n"); 
    });
});

I am trying to make it possible to transfer the content of the <select> box to a <textarea> by selecting the items that need to be transferred.

The problem is that I don't know how to escape the brackets in the name of the <select> box in my jQuery selector.

The solution is to change your selectbox slightly:

<select name="selectemail[]" multiple="true" id="myselect">

$('#myselect') will select the listbox but you can use this jQuery selector to grab the selected options

$('#myselect :selected')

See a working fiddle here .

If you really want to select by name you need to also escape your slashes (because they're in a string) so your selector would be:

$("[name=selectemail\\[\\]] :selected")

There are a two reasons I wouldn't do this:

  1. Selecting by id is much faster than selecting by attribute (I even think selecting by class would be much faster than by name thanks to css).

  2. This is horrible for readability

您应该能够使用反斜杠转义括号,如下所示:

<select name="selectemail\[\]" multiple="true">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM