0

i want some help for an onChange event for 2 drop down lists in javascript. if the 2 lists for example contains exactly the same values. let say A B C D, if the user chooses the B then automatically the B value in the second list should dissapear, if the value D is choosen then the value D in the second list should dissapear etc. Any help pls. i am newbie in javascript.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Taywin
0

What you need to do is one function to compare the value against the other's option list. One thing you did not clarify here is what you are going to do with the selected option a user has selected before the other select option is changed? My sample code below will reset the selected value after hiding + disabling the option from the list. Note that I use CSS to hide it because IE8 (not sure about IE7 and IE9) has a problem with dynamic changing visibility property.

<html>
<style type="text/css">
.hideIt {
  display: none;
  visibility: hidden;
}
</style>

<script type="text/javascript">
function hideOption(selectElementID1, selectElementID2) {
  var el1 = document.getElementById(selectElementID1)
  var el2 = document.getElementById(selectElementID2)
  if (el1 && el2) {  // if both elements exist
    var val = el1.options[el1.selectedIndex].value
    for (var i=0; i<el2.options.length; i++) {
      if (el2.options[i].value==val) {  // same value, hide it
        el2.options[i].disabled = "disabled"
        el2.options[i].className = "hideIt"
        if (el2.selectedIndex >=0) { el2.selectedIndex = -1 }  // reset selected
      }
      else {  // not the same value, ensure that they are displayed
        el2.options[i].disabled = null
        el2.options[i].className = ""
      }
    }
  }
}
</script>

<body>
</body>
<select id="sel1" name="sel1" onchange="hideOption('sel1','sel2')">
 <option value=1>1</option>
 <option value=2>2</option>
 <option value=3>3</option>
 <option value=4>4</option>
 <option value=5>5</option>
</select>

<select id="sel2" name="sel2" onchange="hideOption('sel2','sel1')">
 <option value=1>1</option>
 <option value=3>3</option>
 <option value=5>5</option>
 <option value=7>7</option>
 <option value=9>9</option>
</select>

<script type="text/javascript">
 // run it first to ensure that the first element of both selection
 // are not the same (if the same, the first option of 'sel2' will be hidden.
 hideOption('sel1','sel2')
</script>
</html>

Edited by Taywin: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.