1

I have this JavaScript code that works in Jsfiddle. It makes when the user selects YES on the dropdown, the second one automatically selects NO and vice versa. I have formatted it into my HTML page and for some reason it doesn't work.

I use chrome as a browser. I have added the jsfiddle link and also my HTML code with my JS.

Jsfiddle Link: https://jsfiddle.net/rk57hkak/10/

HTML CODE:

<!DOCTYPE html>
<html>
<body>
  <script src="committee.js"></script>
  <div class="cmicrophone" id="cmicrophone">Currently:
    <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
 <option value="">Select Option</option>
 <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
 <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
    </select>
  </div>  
  <div class="microphone" id="microphone">Microphone:
    <select id="microphone" class="microphone select2" name = "microphone">
 <option value=" "  selected="selected">Select Option</option>
 <option value="ON. Thank you.">ON</option>
 <option value="OFF. Thank you.">OFF</option>
     </select>
   </div>      
</body>
</html>

JavaScript Code:

const cmicrophone = document.querySelector('.select1');
const microphone = document.querySelector('.select2');

function inputHandler(thisSelect, otherSelect) {
  // console.log(thisSelect.selectedIndex)
  if (thisSelect.selectedIndex == 1) {
 otherSelect.selectedIndex = 1;
  } else if (thisSelect.selectedIndex == 2) {
 otherSelect.selectedIndex = 2;
  } else {
 thisSelect.selectedIndex = 0;
 otherSelect.selectedIndex = 0;
  }
}

cmicrophone.addEventListener('input', event => {
  inputHandler(cmicrophone, microphone);
});

microphone.addEventListener('input', event => {
  inputHandler(microphone, cmicrophone);
});
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • 2
    I'm starting to think that jsFiddle and its default values does more harm than good. –  Mar 29 '17 at 14:31

1 Answers1

1

This is because the script is getting executed before the element is present in DOM . In such case lines const cmicrophone = document.querySelector('.select1'); & const microphone = document.querySelector('.select2'); will fail because of the non availability of the element

<body>
  //html code       
<script src="committee.js"></script> // Include script here         
</body>
brk
  • 43,022
  • 4
  • 37
  • 61