What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here:

https://jsfiddle.net/o08r3p9u

I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I ensure that this functionality works as intended?

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55373a3a21262127342515607b65783730213467">[email protected]</a>/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>

Answer №1

Bootstrap offers its own tools for hiding and displaying elements, such as the Collapse component.

This means you can simply use the layout, classes, and data-attributes provided in the documentation, and let Bootstrap handle the rest. For example:

<div class="collapse" id="collapseExample">
  <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>
</div>
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button
</button>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c1ccccd7d0d7d1c2d3e3968d938d938ec1c6d7c291">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534d534d501f18091c4f">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

Answer №2

It seems like there is an issue with the CSS and jQuery code in relation to the display property of the div with id "hideme". The current code sets the display to "block" using elem.style.display, but it should actually be set to "flex". Here is a corrected version of the jQuery code:

Instead of setting elem.style.display = "block";, it should be set as elem.style.display = "flex";, as shown below:

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2e2323383f383e2d3c0c79627c627c612e29382d7e">[email protected]</a>/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>

Answer №3

To find the solution, it's recommended to add an additional container around the input-group div and execute the same function on this new main container div.

For reference, please refer to the JS fiddle: https://jsfiddle.net/cv8oazym/7/

Answer №4

With the power of JavaScript, you can manipulate how elements are displayed on a webpage. When refreshing the input field, instead of setting display to "block", consider using "flex" for more flexibility.

function toggleVisibility() {
  var element = document.getElementById("hide-show");
  if (element.style.display === "none") {
    element.style.display = "flex";
  } else {
    element.style.display = "none";
  }
}

Answer №5

The JavaScript is originally setting the input-group to display: inline-flex, then changing it to display: none, but ultimately ends up applying display: block.

To toggle this behavior, a function called dotoggle() is used which checks the current display property of an element with id "hideme" and toggles it between inline-flex and none.

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

Answer №6

I find the collapse class from Bootstrap to be a convenient solution, eliminating the need for additional JavaScript on our end.

This essentially provides a comprehensive Bootstrap-only approach.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d8d8c3c4c3c5d6c7f782998799879ad5d2c3d685">[email protected]</a>/dist/css/bootstrap.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4c41415a5d5a5a4f5e6e1b001e001e034c4b5a4f30c">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<div class="input-group mb-3 collapse" id="collapseExample">
  <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 class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
BUTTON
</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the Angular directive '=&' value binding to the scope showing as undefined?

An Angular directive has been defined within my application: (function() { 'use strict'; angular .module('almonds') .directive('security', ['$animate', 'AuthFactory', directive]); fun ...

Nested CSS selector within a parent element

How can I change the color of both elements inside a custom button when the button is active? The first color is defined by the class of the button, and the second color is defined by the class of the span inside that button. CSS: .buttonClass{ color:b ...

Issue with nth-child selector not functioning as expected in unordered list

I have a straightforward <nav> setup with an unordered list inside: nav { position: absolute; right: 0px; white-space: nowrap; } nav ul { padding: 0; margin: 0; } nav ul li { clear: both; white-space: nowrap; color: white; displa ...

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

Retrieving data from an API after the onClick event is activated

I'm facing a bit of a challenge with an HTML & JavaScript issue, which I believe should be straightforward to resolve. Since frontend development is not really my forte, I am hoping to find some assistance here. Task: A friend who owns a website buil ...

JavaScript issue: Submitting form does not trigger the associated function

I am currently in the process of learning JavaScript as part of my university course, and I have encountered an issue where my function is not being called. I am seeking to gain a better understanding of why this problem is occurring. Summary The situati ...

Unable to access the suggestion list within the modal

I incorporate the PrimeNG AutoComplete feature within a PrimeNG Dialog, displaying a list of elements below the AutoComplete in the dialog. My objectives are: To set the max-height of the modal dialog to 300, and have a visible scrollbar if the total ...

Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value? <table> <tr> <td>Name</td> <td>John</td> <tr> </table> For instance, how can I apply the color:bl ...

What methods can be employed to stop tests from being included in rollup bundles?

I am currently in the process of creating a react component package and I would like to know how to prevent my tests folder from being included in the dist file that is generated by rollup. After running rollup -c, my directory structure looks like this: ...

Node.js encountered an error: Address already in use. The specified port 8080 is currently being utilized by another application

My application was not functioning properly, and upon running the command "npm start", an error was thrown: Error: listen EADDRINUSE: address already in use :8080 Even after restarting my EC2 instance and attempting the command again, I encount ...

Generate Random Quotes - Each new quote should be different from the previous one

As I tackle the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, everything seemed to be running smoothly except for one major issue - the same quote was often generated two or three times in a row. Obviously, this i ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

Customize the <td> column based on values and rows. Modify the current jQuery code

This code snippet contains an HTML table that dynamically populates based on the dropdown selection. The script included in the code highlights the best and worst values in the table by changing their background color to green and red, respectively. & ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

Styling for Print Media: Adjusting the horizontal spacing between inline elements

I have been developing a custom AngularJS point-of-sale (POS) system that requires printing receipts upon completing a sale. To achieve this, I am using ng-print to print out a sales summary displayed within a specific div element after hiding all other un ...

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

Creating a personalized news feed using getstream.io in Node.js - a step-by-step guide

const stream = require('getstream'); // Setting up a newsfeed stream using getstream const client = stream.connect( null, ); // Defining a feed for user1 var user1 = client.feed('user', 'user1'); // Adding a custom activity ...

Placing numbers at the top of the HTML table cell for better visibility

I am currently utilizing a two-column HTML table to showcase a list of rules. In one column, I have the rule's number, while in the other, I have the rule itself. However, I've noticed that the rule numbers are appearing near the bottom of their ...

Attempting to incorporate a factory within a restricted function

Just starting out with AngularJS and I have a question. Can I use a factory code (logger) inside a private function like the example below? I'm still working on understanding angular concepts. Thanks for your help: (function () { 'use strict ...

I'm interested in finding a data binding framework that connects the DOM, JavaScript, and server-side database in a three-way manner for use with AngularJS and

AngularJS enthusiasts often tout the framework's two-way data binding feature, which allows for seamless synchronization between DOM elements and JavaScript data. Currently, I am immersed in learning projects that involve integrating AngularJS with D ...