1

以前のドロップダウン リストから入力された単純なドロップダウン リストを作成しました。

すべてを選択するにはどうすればよいですか?

以下は、それを設定する JavaScript のコードです。

function OnClkAddButtonServer(form)
{
    var selObj = document.getElementById('List1');
     var selObj2 = document.getElementById('List2');

      var i;
      var count = selObj2.options.length;

      for (i=0;i<selObj.options.length;i++) 
      {
         if (selObj.options[i].selected) 
         {
               var option = new Option(selObj.options[i].text,selObj.options[i].value);
               option.title = selObj.options[i].text;
               selObj2.options[count] = option;
               count=count+1;
               selObj.options[i] = null;
               i--;
         }
      }
}

前もって感謝します

4

2 に答える 2

1

リスト内のすべてのオプションを選択しようとしている場合は、HTML を次のようにする必要があります。

<select multiple="multiple">
  <option selected="selected">Volvo</option>
  <option selected="selected">Saab</option>
  <option selected="selected">Mercedes</option>
  <option selected="selected">Audi</option>
</select>

新しく作成されたオプションを選択できるようにするには、HTML 属性を変更する Javascript メソッドを使用できます。

document.getElementById("idElement").setAttribute("class", "className");

この例では、要素の ID を知っている必要がありますが、別の方法で要素を参照している場合は、無駄なルックアップをスキップできます。

于 2012-07-03T18:04:48.060 に答える
0

まず、すべてのドロップダウン オプションを選択したい場合は、選択タイプが複数であることを確認する必要があります。

たとえば、selObj2 が<select>タグ ( <select id = "List2">) を参照すると仮定すると、select タグに「multiple」属性を追加する必要があります。

<select id = "List2" multiple = "multiple">

JS で実行する場合は、次の行を挿入できます。

selObj2.setAttribute("multiple", "multiple");

また、

selObj2.multiple = true;

これはもちろん、selObj2 が<select>タグであることを前提としています。ただし、複数のオプションを選択するには、複数選択を有効にする必要があります。この属性を有効にしたら、次のステップに進むことができます...

Now, assuming that selObj2.options refers to individual options that you'd like to have selected, you can do this in the JS (just add this block right before the ending brace for the function OnClkAddButtonServer):

for (var i=0; i<selObj2.options.length; i++)
{
    selObj2.options[i].setAttribute("selected", true);
    // or,
    // selObj2.options[i].selected = true;
}

Also, notice in the for loop that I used:

var i=0;

This is because we are creating the variable i local to the scope of the loop, meaning that if we want to use i outside of the loop, the two instances won't conflict. If you didn't use the keyword "var" then the variable i will be accessible anywhere in the whole script (created a global variable). It's a good habit to keep variables local, and since people tend to use i or x as counters in these loops often, it's a good bit of precaution to take in order to avoid any sort of nasty surprises.

于 2012-07-04T07:37:48.777 に答える