1

2番目のリストボックスに同じアイテムを複数回追加することを制限したいのですが、私はそれに非常に近いと思います。助けてください

<script type="text/javascript">
    function CopyFile() {
        var firstListBox = document.getElementById('<%= lstFirstBox.ClientID %>');
        var secondListBox = document.getElementById('<%= lstTarget.ClientID %>');
        for (var i = 0; i < firstListBox.options.length; i++) {
            if (firstListBox.options[i].selected) {
                for (var j = 0; j < secondListBox.options.length; j++) {
                    if (firstListBox.options[i].selected == secondListBox.options[j]) {
                        alert("Multiple selection will not allow");
                    }
                    else {
                        var newOption = document.createElement("option");
                        newOption.text = firstListBox.options[i].text;
                        newOption.value = firstListBox.options[i].value;
                        secondListBox.options[secondListBox.options.length] = newOption;
                        firstListBox.options[i].selected = false;
                    }

                }

            }
        }
        return false;

    }
</script>
4

1 に答える 1

1

私はあなたに例を書きました。次の HTML ページには、2 つの選択項目と 1 つのボタンがあります。最初の選択でオプションを選択してボタンを押すと、そのオプションが 2 番目の選択にコピーされます (まだ選択されていない場合)。最後のケースでは、警告メッセージが表示されます。試すには、ファイル (「test.htm」など) にコピーして貼り付け、ブラウザーで開きます。

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function tryToCopy() {
                var select1 = document.getElementById("select1");
                var select2 = document.getElementById("select2");
                var optionToBeCopied = select1.options[select1.selectedIndex];
                var contains = false;
                for(var i = 0, ceiling = select2.options.length; i < ceiling; i++) {
                    if(select2.options[i].value == optionToBeCopied.value) {
                        contains = true;
                        break;
                    }
                }
                if(contains) {
                        alert("duplicate options are not allowed.");
                } else {
                    var option = document.createElement("option");
                    select2.appendChild(option);
                    option.value = optionToBeCopied.value;
                    option.text = optionToBeCopied.text;
                }
            }
        </script>
    </head>
    <body>
        <select id="select1">
            <option value="" selected="true"></option>
            <option value="a">a</option>
            <option value="b">b</option>
        </select>
        <select id="select2">
        </select>
        <input type="button" value="tryToCopy" onclick="tryToCopy()"/>
    </body>
</html>
于 2012-08-03T12:20:36.247 に答える