How can one hide / show an input-group in Bootstrap

I’m trying to hide / show a Bootstrap 5 input-group as shown here:

https://jsfiddle.net/o08r3p9u

However, once hidden, the input group no longer shows correctly when shown again. How can this functionality be properly implemented?

function dotoggle() {
  elem = document.getElementById("hideme")
  if (elem.style.display == "none") {
    elem.style.display = "block";
  } else {
    elem.style.display = "none";
  }
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="input-group mb-3" id="hideme">
  <span class="input-group-text" id="basic-addon1">@</span>
  <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
</div>

<button onclick="dotoggle()">
BUTTON
</button>

27 thoughts on “How can one hide / show an input-group in Bootstrap”

  1. Because the div #hideme uses the flex display (.input-group class), but in the jquery code you specify the elem.style.display = "block";. And this is not correct.

    In the jquery code, specify the elem.style.display = "flex";, like here:

    function dotoggle() {
      elem = document.getElementById("hideme")
      if (elem.style.display == "none") {
        elem.style.display = "flex";
      } else {
        elem.style.display = "none";
      }
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="input-group mb-3" id="hideme">
      <span class="input-group-text" id="basic-addon1">@</span>
      <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
    </div>
    
    <button onclick="dotoggle()">
    BUTTON
    </button>
    Reply
  2. It is from the javascript written.
    You are setting the display to "block" when re-rendering the input.
    Set display to "flex"

    function dotoggle() {
      elem = document.getElementById("hideme")
      if (elem.style.display == "none") {
        elem.style.display = "flex";
      } else {
        elem.style.display = "none";
      }
    }
    
    Reply
  3. Your JavaScript is applying a display: block instead of a display: inline-flex.

    So at start the input-group is set to display: inline-flex, then set to display: none but then is changed to block instead.

    function dotoggle() {
      elem = document.getElementById("hideme")
      if (elem.style.display == "none") {
        elem.style.display = "inline-flex";
      } else {
        elem.style.display = "none";
      }
    }
    
    Reply

Leave a Comment