Skip to content Skip to sidebar Skip to footer

Show/hide Element Without Inline Javascript

I am trying to show/hide an element with raw Javascript when a radio button has a specific value. I can get it to work with inline Javascript, but I want to try and do it using th

Solution 1:

Problem #1: dog is never defined. I believe you want to check if the value of the changed element is dog, so you should do this instead:

if (this.value == "dog") {

Problem #2: getElementsByName needs to be called as a method of another object (usually document)

var typeOfPet = document.getElementsByName('petType');

Problem #3: AddEventListener should have a lowercase a. It also can't be applied to a node collection, which getElementsByName returns. You should loop through each element instead.

for(var i = typeOfPet.length; i--;) {
    typeOfPet[i].addEventListener('change', asdf, false);
}

Working version: http://jsfiddle.net/nderscore/ePDx9/6/

Solution 2:

Try:

functionasdf(x) {
     var breed = document.getElementById('breed');
     if (this.value === "dog") { //Look for this.value for dog.
         breed.style.display = "inline";

     } else {
         breed.style.display = "none";
     }
 }

 var typeOfPet = document.getElementsByName('petType'); //Get the elements by namefor (var i = 0, l = typeOfPet.length; i < l; i++) { //Loop through them
     typeOfPet[i].addEventListener('change', asdf, false); //Bind listener to them each of them.
 }

Demo

  • getElementsByName is not a standalone method it needs to be applied on document or element.
  • getElementsByName returns a node collection (live), so you need to loop though them and apply binding on each of them.
  • Casing of addEventListener and binding on the element was incorrect.
  • In order to look for the value of current radio just use this.value and do the comparison

Post a Comment for "Show/hide Element Without Inline Javascript"