Toggle visibility of cards using bootstrap

I've been attempting to show and hide a selection of cards in bootstrap, but I'm having trouble figuring it out. All the cards share the class "card," and my goal is to hide them all when a specific button is clicked. Below is my current code:

function myFunction() {

  jQuery(document).ready(function($) {
    $(".card").hide();
  });

  var game = document.getElementById("game").value;
  var resolution = document.getElementById("resolution").value;
  var graphic = document.getElementById("graphic").value;

  if (game == "Black" && graphic == "high" && resolution == "1080") {
    alert("Hello " + game + "! You will now be redirected to www.w3Schools.com");
  } else if (book == "Red") {

  } else if (book == "Green") {

  } else {

  }
}

The function call appears to be correct as the alert is functioning properly.

Interestingly, the

jQuery(document).ready(function($) {
        $(".card").hide();
      });

segment of code works when placed outside of the JS function, but not when connected to the button click event.

It may or may not be relevant, but here is a snippet of my Bootstrap document as well:

<button type="submit" class="btn btn-primary" id="btn" onclick="myFunction()">Submit</button>
          </form>
        </div>
        <!-- Results -->
        <div class="card" id="p2" style="width:200px; margin:30px">
          <img class="card-img-top" src="https://image" alt="Card image" style="width:100%">
          <div class="card-body">
            <h5 class="card-title">Processor</h5>
            <p><a href="#">Newegg</a></p>
            <p><a href="#">Newegg</a></p>
            <p><a href="#">Newegg</a></p>
          </div>
        </div>
        <div class="card" id="p3" style="width:200px; margin:30px">
          <img class="card-img-top" src="https://image" alt="Card image" style="width:100%">
          <div class="card-body">
            <h5 class="card-title">Graphic card</h5>
            <p><a href="#">Newegg</a></p>
            <p><a href="#">Newegg</a></p>
            <p><a href="#">Newegg</a></p>
          </div>
        </div>

Here are the methods I've tried so far:

Using the toggle method How to hide and show bootstrap 4 cards by hovering over navigation menu through CSS?

Directly modifying the display property with standard JS: document.getElementById(".card").style.display = "none";

I've also looked into React techniques, but I'm not quite grasping it.

Answer №1

If you're looking to create a toggle effect for all elements with the "card" class in your DOM, you can achieve this by following these steps:

var toggleCards = function() {

 var elementsToToggle = document.getElementsByClassName("card"); 
if(elementsToToggle.length>0){
        for(var i = 0; i < elementsToToggle.length; i++){

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

           elementsToToggle[i].style.display = "none"; // You can customize this based on your needs
      }    
}} }

I hope this solution is helpful for your project.

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

Toggle the visibility of a section in an external .js file

Is there a way to toggle the display of answers from an external .js file using a button? If I were able to modify the code, I could wrap the answers in a div. However, since it's an external .js file, is this feasible? Here's the fiddle and cod ...

Are there any other options available in JavaScript to replace the .unload() function?

I have a click event attached to multiple buttons on my page, each loading a different .php file into the same div. The issue arises when the time to load increases after several clicks. $('#start').click(function() { $('#mainbody&apos ...

Display geographic data using d3 with geoJSON

I am struggling to render a geoJSON file using d3 because I am having trouble targeting the correct features for projection. Instead of working with the typical us.json file used in many d3 examples, my current map focuses on United States "Commuting Zone ...

Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email a ...

Guide on automatically navigating pages using HTML

My dilemma involves two HTML pages: flash.html main.html I am seeking a solution where the flash.html page is loaded first for 5 seconds, after which the main.html page should automatically load. How can I achieve this? I attempted to use setTimeout(fu ...

Instructions on how to activate scrolling for a div element that becomes visible upon clicking a button

When a button in the navbar is clicked, a div appears with a height that exceeds the viewport/page size. How can I enable scrolling for the entire page when this happens? I attempted to use overflow: scroll, but it only applied scrolling to the internal d ...

The functionality of the Eslint object-property-newline feature is not functioning as expected

Within my configuration file .eslintrc, I have set "object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }], and "max-len": "off". However, objects like const something = {a: 5, ffsdfasdasdsddddd: 'asdasdasdddddddddddssssssddddd ...

Using jQuery to pass an array as part of an object literal for AJAX data transmission

I'm currently facing an issue with passing a dynamic object to jQuery ajax data in order to mimic the structure of serialized form data. This problem arises when I have a form with inputs using an array for the name, as shown below: <input type="t ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

What is the best approach to have a React page render only the specific component that has changed, rather than re

Recently, I've been facing an issue with a toggle implementation where the page always re-renders the entire content upon the first click of the toggle. Here is a snippet of how it looks: export default function Toggle({isChecked, label}: Props) { r ...

Encountering an "Angularjs 1.2.x Injector:modulerrr" error, even after successfully incorporating ngRoute

I am currently learning angularjs and I have encountered a persistent error. Despite multiple attempts at troubleshooting, I have been unable to resolve it. Here is the code that I have: index.html <!doctype html> <html ng-app="myApp"> <he ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

What is the best way to verify the accuracy of my model when it includes an array property?

One of the challenges I am facing is dealing with a class that has an array property in MVC. public class MyClass { public int Contrato_Id { get; set; } public string Contrato { get; set; } public int Torre_Id { get; set; } public string T ...

The personalized confirmation dialog is experiencing malfunctions

I have designed my own custom dialogs using Bootstrap and jQuery, such as Alert and ConfirmDialog. Here is a sample: http://jsfiddle.net/eb71eaya/ The issue I am facing is that in the callback function, I make an AJAX call. If it returns true, I want to ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...

What is the best way to successfully implement multiple post requests using Django and Ajax on a single webpage?

After spending the entire day struggling with this issue, I am still unable to make any progress. Let me explain my predicament. In my Django form, I have two fields: redirect_from and redirect_to. The form contains two buttons: Validate and Save. Initial ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

What is the best way to incorporate an array of elements into Firebase?

How can I store data from an array to Firebase in a simple manner? Let's say I have an array of elements. function Something() { var elements=new Array() elements[0]=10; elements[1]=20; elements[2]=30; database = firebase.databas ...

What causes React Router to render the Navigation to the <Home/> component when the userData is still available, but redirects to "/login" otherwise?

I'm currently developing a Note-taking application using React with React Router for navigation. For creating routes, I am utilizing createBrowserRouter(). Below is the code snippet: import './App.css'; import NoteList from "./componen ...