根据使用Javascript在另一个下拉列表中选择的内容设置下拉值,反之亦然

时间:2017-10-05 18:36:07

标签: javascript html

我看到了答案

Set dropdown value based on what is selected in another dropdown using Javascript

我想要另一只手。当在select id = b上选择一个元素时,重置select on id = a,example

选择“另一个选项1”,id = a设置为“---”

为什么不工作?

HTML:

<select id="a" onchange="changedrop();">
  <option value="1">---</option>
  <option value="2">option 1</option>
  <option value="3">option 2</option>
  <option value="4">option 3</option>
</select>
<select id="b" onchange="changedrop();">>
  <option value="1">---</option>
  <option value="2">another option 1</option>
  <option value="3">another option 2</option>
</select>

JS:

function changedrop() {
  if (document.getElementById('a').value == '1')
  document.getElementById("b").value = '1';
  else if (document.getElementById('a').value == '2')
  document.getElementById("b").value = '1';
  else if (document.getElementById('a').value == '3')
  document.getElementById("b").value = '1';
  else if (document.getElementById('a').value == '4')
  document.getElementById("b").value = '1';
  else if (document.getElementById('b').value == '1')
  document.getElementById("a").value = '1';
  else if (document.getElementById('b').value == '2')
  document.getElementById("a").value = '1';
  else if (document.getElementById('b').value == '3')
  document.getElementById("a").value = '1';
};

1 个答案:

答案 0 :(得分:0)

问题是您需要在onchange元素上收听select事件。

&#13;
&#13;
function changeDropA() {
  var a = document.getElementById('a');
  var b = document.getElementById("b");
  
  if (a.value == '1')
    b.value = '1';
  else if (a.value == '2')
    b.value = '1';
  else if (a.value == '3')
    b.value = '1';
  else if (a.value == '4')
    b.value = '1';
};

function changeDropB() {
  var a = document.getElementById('a');
  var b = document.getElementById("b");

  if (b.value == '1')
    a.value = '1';
  else if (b.value == '2')
    a.value = '1';
  else if (b.value == '3')
    a.value = '1';
}

document.getElementById('a').addEventListener('change', changeDropA);
document.getElementById('b').addEventListener('change', changeDropB);
&#13;
<select id="a">
  <option value="1">---</option>
  <option value="2">option 1</option>
  <option value="3">option 2</option>
  <option value="4">option 3</option>
</select>
<select id="b">
  <option value="1">---</option>
  <option value="2">another option 1</option>
  <option value="3">another option 2</option>
</select>
&#13;
&#13;
&#13;