-2

I have a dropdown list that is repeated 30 times on a page. I have created a function that should take care of the value, but every time I step through in the browser the variable is always null.

I am calling my select like this:onchange="showDropDown(capability_4_1_b,this.value)"

my function:

function showDropDown(id,value) {
var nc = document.getElementById(id);
  if (value === "NC" || value === "OBS") {
      nc.style.display = 'block';
  } else {
      nc.style.display = 'none';
  }
}

The div I am targeting is <div id="capability_4_1_b" style="display:none;">

I have looked in the source and the element is in the DOM my JS files are at the bottom of the page. Developer tools

The function above is how I started doing the functions but I want to achieve this with one function. The functions work but too much repetition :).

StudentRik
  • 1,039
  • 2
  • 18
  • 34

4 Answers4

2

capability_4_1_b is a variable. The browser is resolving it into an Element object. The JavaScript is then converting it to a string and then trying to find an element with an ID that matches it.

You need to pass a string instead.

onchange="showDropDown(&quot;capability_4_1_b&quot;,this.value)"
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
1
onchange="showDropDown(capability_4_1_b,this.value)"

You didn't quote capability_4_1_b, so it's not working.

onchange="showDropDown('capability_4_1_b',this.value)"
Scimonster
  • 31,931
  • 8
  • 74
  • 86
0

You'll need to pass an actual string:

onchange="showDropDown('capability_4_1_b', this.value)"
                       ^                ^

Otherwise, you're actually passing the element itself, that's the reason why you don't get an error.

Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
0

Just modify your onchange method call from

onchange="showDropDown(capability_4_1_b,this.value)"

To

onchange='showDropDown("capability_4_1_b",this.value)'

You are passing the id which should be in string format so need to write in double quotes.

Atish Bundhe
  • 545
  • 2
  • 6
  • 13