Move buttons from one group to another group

I have a task to update a group of buttons with different buttons depending on the initial button chosen.

  • Button1: when clicked, both buttons will be replaced by Button1a and Button1b

  • Button2: when clicked, both buttons will be replaced by Button2a and Button2b

This is what I have done so far:

<div class="buttons">
  <div class="buttons1-2">
    <button type="button" class="btn btn1">Button 1</button>
    <button type="button" class="btn btn2">Button 2</button>
  </div>
  <div class="buttons1a-b">
    <button type="button" class="btn btn1a">Button 1a</button>
    <button type="button" class="btn btn1b">Button 1b</button>
  </div>    
  <div class="button2a-b">
    <button type="button" class="btn btn2a">Button 2a</button>
    <button type="button" class="btn btn2b">Button 2b</button>
  </div>    
</div>

I have hidden the 1a-b and 2a-b buttons:

.button1a-b {
    display: none;
}
.button2-b {
    display: none;
}

However, I am having trouble writing the JavaScript code for this functionality. Can anyone assist me in coding this in JavaScript? Additionally, if there is a more efficient way to structure my HTML/CSS for this task, please share your recommendations.

Answer №1

One way to achieve this is by using the onClick() function.

function handleButtonClick(btn) {
  var replaceWith = "buttons1a-b";
  if (btn.id == "btn2") {
    replaceWith = "buttons2a-b";
  }

  var allChildren = document.getElementsByClassName('buttons')[0].children;
  for (var i = 0; i < allChildren.length; i++) {
    var child = allChildren[i];
    if (child.className != replaceWith) {
      child.style.display = "none";
    } else {
      child.style.display = "inline";
    }
  }

}
.buttons1a-b {
  display: none;
}

.button2a-b {
  display: none;
}
<div class="buttons">
  <div class="buttons1-2">
    <button id="btn1" class="btn btn1" onclick="handleButtonClick(this)">Button 1</button>
    <button id="btn2" class="btn btn2" onclick="handleButtonClick(this)">Button 2</button>
  </div>
  <div class="buttons1a-b">
    <button class="btn btn1a">Button 1a</button>
    <button class="btn btn1b">Button 1b</button>
  </div>
  <div class="button2a-b">
    <button class="btn btn2a">Button 2a</button>
    <button class="btn btn2b">Button 2b</button>
  </div>
</div>

Answer №2

While it may not be the most optimal solution, it should suffice for your needs. Essentially, I created an event listener for each button click. This way, when a button is clicked, the hidden buttons are displayed while the current button is hidden.

document.getElementById('btn1').addEventListener('click', function() {
  changeButtons(document.getElementsByClassName('buttons1a-b'), 'block');
  this.style.display = "none";
  document.getElementById('btn2').style.display = "none";
});
document.getElementById('btn2').addEventListener('click', function() {
  changeButtons(document.getElementsByClassName('button2a-b'), 'block');
  document.getElementById('btn1').style.display = "none";
  this.style.display = "none";
});

function changeButtons(coll, display) {

  for (var i = 0, len = coll.length; i < len; i++) {
    coll[i].style["display"] = display;
  }
}
.buttons1a-b {
  display: none;
}

.button2a-b {
  display: none;
}
<div class="buttons">
  <div class="buttons1-2">
    <button id="btn1" type="button" class="btn btn1">Button 1</button>
    <button id="btn2" type="button" class="btn btn2">Button 2</button>
  </div>
  <div class="buttons1a-b">
    <button type="button" class="btn btn1a">Button 1a</button>
    <button type="button" class="btn btn1b">Button 1b</button>
  </div>
  <div class="button2a-b">
    <button type="button" class="btn btn2a">Button 2a</button>
    <button type="button" class="btn btn2b">Button 2b</button>
  </div>
</div>

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

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

Manipulate HTML elements using JavaScript when a key is being held down

I'm currently developing a simple game using vueJS for the frontend. I have successfully created all the necessary objects and now my goal is to enable their movement when a key is pressed. However, I am facing an issue where the object only moves on ...

verify access with mysql database

Need urgent assistance, sorry if this is a repeated query due to my username! I am facing an issue with my login page. I want it to redirect to my home page when authentication fails by cross-checking input with a MySQL database which should output succes ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

Unable to retrieve information from localhost site using the expressjs API. I have attempted to use both vue-resource and axios in order to get the data without success

Currently diving into the world of VueJS, I decided to embark on a project. My aim is to retrieve data from an ExpressJS server/API. But unfortunately, both vue-resource and axios have been returning status code 0. It seems like my API might not be handli ...

Prevent content from occupying unnecessary space below a sticky div

When the "link" on the sticky header is clicked in this scenario, how can I ensure that the linked content item (#mypara) appears below the sticky div rather than directly underneath it where it may be hidden? $(document).ready(function() { $(window ...

Guide to showcasing associated information in HTML using Angular 7

I am a beginner with Angular 7 and I am attempting to showcase a product's color on the HTML side using Angular 7 but have not been successful. Below are my tables; Product Id Name Color Id Name ProductColorRelation Id ProductId ColorId In ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

bcrypt is failing to return a match when the password includes numeric characters

I've integrated node-bcrypt with PostgreSQL (using Sequelizejs) to securely hash and store passwords. In the process, the user's password undergoes hashing within a beforeValidate hook as shown below: beforeValidate: function(user, model, cb) { ...

Challenges with KendoUI integration

In one of my web pages, I have a combination box and a checkbox. To enhance the functionality, I decided to utilize the KendoUI library. The combo box allows users to choose between two options - 0% and 100%. If the checkbox is selected, the combo box shou ...

One issue with my Quiz app is that sometimes the correct and incorrect answer methods run concurrently, leading to occasional occurrences of this problem

One issue I encountered while developing a Quiz app is that sometimes the methods for correct and incorrect answers run simultaneously. This problem occurs sporadically. I want to highlight that my code is functioning correctly. The only challenge I face ...

Creating a vertical bar chart in D3 with a JSON data source embedded within the code

Struggling to generate a stacked bar graph in D3.js. The axes are displaying correctly, but the data on the graph is not showing up. Any suggestions on what could be causing this issue? JS: var svg = d3.select("#recovery__table"), margin = {top: 20, ...

What could be causing the error 404 message to appear when trying to retrieve video data?

I'm having trouble displaying a video in mp4 format from the code's folder. When I attempt to fetch the video by clicking on the button, it shows an empty space instead of displaying the video. Here is an example of what the output looks like. T ...

No need for jQuery with this scrolling image gallery

I recently created a horizontal scrolling image gallery with thumbnails underneath. The goal is to click on a thumbnail and have the corresponding image scroll into view. Here's the HTML setup: <div class="images_container"> <img id="imag ...

Leverage VueJS and VueX to seamlessly integrate firebase 9 functions within my application

I am currently in the process of developing a blog application using Firebase version 9, VueJs version 3, and VueX. All functionalities such as user registration and authentication are working smoothly. However, I encountered an error when attempting to a ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

What is the best way to attach a Label to a THREE.Mesh object?

I'm looking to show the name of a Three.js Three.Mesh as a label when hovering over the mesh. Does anyone know how to achieve this in Three.js? Could someone provide an example code snippet for this? ...

Instant webpage updates upon editing CSS/HTML live

I recently watched a tutorial where a designer was updating CSS with live browser refreshes. What stood out to me was that the browser instantly showed any changes made to the CSS or HTML without needing to manually refresh the page. I am using a Mac with ...

The width of the Ion-slide is dynamically determined by the styling

After transitioning my Ionic 2 project to Ionic 3, I encountered issues with ion-slides which are affecting my app's functionality. Upon app loading, specific widths are being defined in the style tags on the slides, disrupting the intended styling. ...

Warning: Potential unhandled promise rejection in React class component

I'm trying to implement a promise inside a class so that depending on whether it resolves or rejects, another method of my component is executed. Below is the code I have: var promise = new Promise((resolve, reject) => { let name = 'DaveA&ap ...