0

私は2つの選択ドロップダウンを持っており、それぞれにたくさんの要素があります(以下の例)。

<select id="one">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

<select id="two">>
<option>2</option>
<option>4</option>
<option>6</option>
<option>8</option>
</select> 

最初のドロップダウン要素が選択されているときに、2 番目のドロップダウンにいくつかのオプションを表示するにはどうすればよいですか。(たとえば、ドロップダウン #1 で 1 を選択した場合、ドロップダウン #2 で 1+2=2 オプションを非表示にする必要があります。#1 で 2 を選択した場合、2+2=(4) を #2 で非表示にする必要があります。など

次のような方法でアプローチする必要があると思います。

        document.getElementById("one").onchange = function( ){
            var selectedOption = document.getElementById("one").options[document.getElementById("one").selectedIndex].text; 
        }

次に何をすべきですか?

4

3 に答える 3

3

jQuery を使用しない場合:

document.getElementById("one").onchange = function( ){
    var selectedOption = this.options[this.selectedIndex].text;

    var option = getElementByText(document.getElementById("two"), selectedOption * 2);
    option.style.display = "none"; // or u car remove it here
}

function getElementByText(parent, text) {
    for (var i = 0; i < parent.children.length; i ++) {
        if (parent.children[i].text == text) {
            return parent.children[i];
        }
    }
    return false;
}

jsfiddle

于 2012-05-25T05:58:02.497 に答える
2

1 を選択すると 2 が削除され、2 を選択すると 4 が削除され、3 を選択すると 6 が削除され、4 を選択すると 8 が 2 番目のドロップダウンから削除されます。

  <script>
    function updateSet2(sel){
      var select2 = document.getElementById("two");
      select2.options.length = 0; //clear

      //repopulate
      select2.options[0] = new Option('2', '2');
      select2.options[1] = new Option('4', '4');
      select2.options[2] = new Option('6', '6');
      select2.options[3] = new Option('8', '8');

      //remove selected
      select2.options.remove(sel - 1);
    }

    var select1 = document.getElementById("one");
    select1.onchange = function(e){
      var selected = this.options[this.selectedIndex]
      updateSet2(selected.text);
    }
  </script>
于 2012-05-25T05:56:47.450 に答える
1

別のオプション:

<script>
var doChange = (function() {
  var storedSel;

  return function () {
    var sel0 = this;
    var sel1 = sel0.form.sel1;
    var opt;

    storedSel = storedSel || sel1.cloneNode(true);

    // Show all options of sel1
    sel1.parentNode.replaceChild(storedSel.cloneNode(true), sel1);
    sel1 = sel0.form.sel1;

    // Hide some based on selection
    if (sel0.value == 1) {
      sel1.removeChild(sel1.options[3]);
      sel1.removeChild(sel1.options[1]);

    } else if (sel0.value == 2) {
      sel1.removeChild(sel1.options[2]);
    }
  }
}());

window.onload = function() {
  document.forms.f0.sel0.onchange = doChange;
}
</script>

<form id="f0">
  <select name="sel0" size="4">
    <option value="0">0
    <option value="1">1
    <option value="2">2
    <option value="3">3
  </select>
  <select name="sel1" size="4">
    <option value="4">4
    <option value="5">5
    <option value="6">6
    <option value="7">7
  </select>
</form>
于 2012-05-25T07:21:36.903 に答える