Problem making inputs appear and disappear with jquery

Asked

Viewed 258 times

1

I need to do some inputs on my form of the mobile version are hidden and displayed by clicking on the button called Busca avançada I created a code jQuery but it’s not working I don’t know what I’m doing wrong remembering I’m using bootstrap 4 follow my codes:

HTML:

Type Reporting period 2 3 4 5 Number Year Choose a year 2 3 4 5 Search by term Fetch
            <button class="d-block d-sm-none advanced-btn" onclick="myFunction()">Busca avançada <i class="fas fa-caret-down"></i></button>

SCSS:

.advanced-btn{
    border: 0;
    background-color: transparent;
    outline: none;
}
@media (max-width: $screen-xs-min) {
    .myDIV{
        display: none;
    }
}

JS:

function myFunction() {
    var x = document.getElementsByClassName("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

1 answer

1


Face if it’s just to show off the contents of div can do as in the example, but, follows some considerations:

  • 1 - If you leave the class d-sm-none on the button as is your code, the button will stay with display None and will not have to click it to appear the div you want.
  • 2 - You said you made a code with jQuery, but his example is with Javascript.
  • 3 - Because it didn’t work, the Document.getElementByClassName() by default returns a Nodelist, that is, an array of elements, which in order to be accessed it is necessary to indicate an index as for example [0].

var x = document.getElementsByClassName("myDIV");
x[0].style.display = "none";

function myFunction(){

    if(x[0].style.display == "none"){
      x[0].style.display = "block";
    }else{
      x[0].style.display = "none";
    }

    // x[0] pega a primeira div, se tivesse uma outra div com esta classe 
    // vc pegaria ela com x[1]
    
}
#myDIV{
  margin: 10% 25%;
}
.advanced-btn{
    border: 0;
    background-color: transparent;
    outline: none;
}
@media (max-width: $screen-xs-min) {
    .myDIV{
        display: none;
    }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css">

<button class="btn d-block advanced-btn" onclick="myFunction();">Busca avançada <i class="fas fa-caret-down"></i></button>

<div class="myDIV" id="myDIV">
  <input class="form-control" type="text" placeholder="texto qualquer">
  <br>
  <input class="form-control" type="text" placeholder="texto qualquer">
</div>

  • It doesn’t close back ? I needed it to close up tbm

  • I edited the answer Kirito.

  • 1

    If the answer was useful to you, consider accepting it so that it can be closed on the site.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.