-1

I wanted to make a specific form show and the other forms disappear when I click on one of four dropdown buttons. When I tested the code, no from is showing when I clicked on a button.

Here is my javascript code:

function showClass(className)
{
    var allItems = document.getElementsByClassName('change-form');
    for (var i = 0; i < allItems.length; i++)
    {
        allItems[i].style.display = "none";
    }
    var formItems = document.getElementsByClassName(className);
    for (var i = 0; i < formItems.length; i++)
    {
        formItems[i].style.display = "block";
    }
}

It shows the form if I remove the top for loop. Edit: Sorry guys I made a typo

  • I don't see a question here. – Filip Seman Apr 03 '21 at 19:49
  • 1
    `allItems` and `formItems` are going to be the same elements, so you are setting them all to `none` and then immediatly to `block` – Patrick Evans Apr 03 '21 at 19:51
  • At first, see https://stackoverflow.com/a/66480319/1169519 . Secondly, the code does the job as expected (providing a correct classname has been passed). Thirdly, don't use the DOM as a model, it's purposed to store the view of your page. Instead, store the last visible form into a variable, and hide that form using the stored reference in that variable, then use the value attribute, or what ever you have at hands, to show the new form. – Teemu Apr 03 '21 at 19:52
  • Instead of changing CSS properties in a loop, use CSS classes, e.g. `.parentCls .cls1 { display: block; } .parentCls .cls2 { display: none; } .parentCls.toggled .cls1 { display: none; } .parentCls.toggled .cls2 { display: block; }`; then simply [`parent.classList.toggle("toggled")`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods) or something similar. Consider using the [`hidden` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Apr 03 '21 at 19:57

1 Answers1

0

Your code is going in and hiding all the items and then showing them right away. What you want to do is split the hide and show into different functions to trigger them at different times.

function showClass(className)
{
    var formItems = document.getElementsByClassName(className);
    for (var i = 0; i < formItems.length; i++)
    {
        formItems[i].style.display = "block";
    }
}

function hideClass(className){
    var allItems = document.getElementsByClassName(className);
    for (var i = 0; i < allItems.length; i++)
    {
        allItems[i].style.display = "none";
    }
}

If you want to be able to swap them with one function you could use this:

function swapHide(className){
    var firstItem = document.getElementsByClassName(className)[0];
    var isDisplayed = firstItem.style.display == "block"
    if(isDisplayed){
        hideClass(className);
    }else{
        showClass(className)
    }
}
Ntjs95
  • 128
  • 1
  • 8