动态选择html中的所有选项 [英] select all options in html select dynamically
问题描述
我在表单中有两个HTML选择。第一个被称为可用
并且包含多个选项:
I have two HTML selects in a form. The first is called available
and contains several options:
<select name="sortedby" multiple="multiple">
<option value="start">
<xsl:if test="@sortedby='start'">
<xsl:attribute name="selected">true</xsl:attribute>
</xsl:if>
Start time
</option>
<option value="thread_id">
<xsl:if test="@sortedby='thread_id'">
<xsl:attribute name="selected">true</xsl:attribute>
</xsl:if>
Thread Id
</option>
<option value="user_name">
<xsl:if test="@sortedby='user_name'">
<xsl:attribute name="selected">true</xsl:attribute>
</xsl:if>
Username
</option>
</select>
第二个名为 yourselection
且为空在开始时:
The second is called yourselection
and is empty at the beginning:
<select name="sortedby_target" multiple="multiple">
</select>
有一个按钮可以从可用
并将它们移动到 yourselection
。
There is a button which removes the selected options from available
and moves them to yourselection
.
这个按钮从我可以使用的库调用JavaScript函数但不能修改。
This button calls a JavaScript function from a library that I can use but can't modify.
基本上它工作正常。但是有一点小小的不便:当用户从可用
到 yourselection
移动一个或多个选项时,它们在抵达时没有被默认选择。因此,目前用户必须首先在 available
中选择一个选项,然后将其移至 yourselection
,然后再次手动将其选中 yourselection
,然后提交表单。
Basically it works fine. But there is a minor inconvenience: When the user moves one or several option(s) from available
to yourselection
, they are not selected by default "upon arrival". So currently the user has to select an option first in available
than move it to yourselection
, and again manually select it in yourselection
, and then submit the form.
我想要的是,到达 yourselection
的所有内容都应该标记为默认选择。任何想法?
What I want is everything that arrives to yourselection
should be marked as selected by default. Any ideas?
更新!我有一个可以选择所有元素的函数:
UPDATE! I have a function that can select all elements:
function selectAllOptions(obj) {
if (!hasOptions(obj)) { return; }
for (var i = 0; i < obj.options.length; i++) {
obj.options[i].selected = true;
}
}
但问题是如何调用它?我不想为此添加另一个按钮。
But the question is how to call it? I do not want to add another button for that reason.
应该有类似于 onfill
或类似的内容选择。
There should be something like onfill
or something similar in select.
推荐答案
<form name="jmxForm" onsubmit="selectAllOptions(sortedby_target)">
....
</form>
function selectAllOptions(obj) {
if (!hasOptions(obj)) { return; }
for (var i=0; i<obj.options.length; i++) {
obj.options[i].selected = true;
}
}
这篇关于动态选择html中的所有选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!