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:
在Javascript文件中,我有以下内容:
$("#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.
问题是我不知道如何在我的jQuery选择器中的
2 个解决方案
#1
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')将选择列表框,但您可以使用此jQuery选择器来获取所选选项
$('#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:
我不这样做有两个原因:
-
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).
按id选择要比按属性选择要快得多(我甚至认为按css选择按类别比名称要快得多)。
-
This is horrible for readability
这对可读性来说太可怕了
#2
You should be able to use backslashes to escape the brackets, like this:
您应该能够使用反斜杠来转义括号,如下所示:
<select name="selectemail\[\]" multiple="true">
#1
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')将选择列表框,但您可以使用此jQuery选择器来获取所选选项
$('#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:
我不这样做有两个原因:
-
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).
按id选择要比按属性选择要快得多(我甚至认为按css选择按类别比名称要快得多)。
-
This is horrible for readability
这对可读性来说太可怕了
#2
You should be able to use backslashes to escape the brackets, like this:
您应该能够使用反斜杠来转义括号,如下所示:
<select name="selectemail\[\]" multiple="true">