Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

javascript - select all options in html select dynamically

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>

The second is called yourselection and is empty at the beginning:

<select name="sortedby_target" multiple="multiple">
</select>

There is a button which removes the selected options from available and moves them to yourselection.

This button calls a JavaScript function from a library that I can use but can't modify.

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.

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.

There should be something like onfill or something similar in select.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    <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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...