Home > Back-end >  Why does my JS function only affect the first element addressed in the HTML structure? (changing dis
Why does my JS function only affect the first element addressed in the HTML structure? (changing dis

Time:04-08

my basic structure of the JS function works. However, it only affects the first DIV in the HTML structure that is to be shown and hidden.

The CSS class "map-content" has none as display property. Several containers will receive this class and will therefore initially be hidden. All DIV containers get their own value, which is necessary in my code when changing the display property.

This is my function, which basically works, but only shows and hides the first container (in the HTML structure) with the "map-content" class.

function validate_3() {
    
  var x = document.getElementById("location_select");
  var y = x.options[x.selectedIndex].value;
  var a = document.querySelector(".map-content");
  var b = a.getAttribute('value');
    
  {
    if (y == b) {
        a.style.display = "block";
    } else {
        a.style.display = "none";
    }
  }
}
.map-content {
  display: none;
}
<select id="location_select" onchange="validate_3">
  <option disabled selected>Select location...</option>
  <option value="de_germany">Berlin: Germany</option>
  <option value="fr_france">Paris: France</option>
  <option value="it_italy">Rome: Italy</option>
</select>

<div  value="de_germany">
  <h3>This is Berlin</h3>
  <p>Berlin is in Germany</p>
</div>

<div  value="fr_france">
  <h3>This is Paris</h3>
  <p>Paris is in France</p>
</div>

<div  value="it_italy">
  <h3>This is Rome</h3>
  <p>Rome is in Italy</p>
</div>

Note on the code snippet: I don't know why, but unlike my test interface, none of the selections work here. Not even the first in the structure as described in the text.

I am happy to get general suggestions for a better structure if there are any.

CodePudding user response:

you are missing a set of parentheses here onchange="validate_3"> , add a set of parentheses like this onchange="validate_3()">, and your first selection should work

To get what you want, make sure you've added the parentheses as shown above.

javascript,

// take this line out of your funtion and change `querySelector` to
//`querySelectorAll`
var a = document.querySelectorAll(".map-content");

function validate_3() {
    
  var x = document.getElementById("location_select");
  var y = x.options[x.selectedIndex].value;

//use The forEach() method to executes a provided function once for each
//element. 
  a.forEach((element) => {
  if (y != element.getAttribute("value")) {
  (element.classList.add("map-content"))
  } else {
  element.classList.remove("map-content")
  };
  });
};

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

  • Related