`Switch up the backdrop upon selection`

I'm experimenting with bootstrap and hit a roadblock. I have radio buttons that I want to outline when not selected, and appear solid or "btn-primary" when selected.

I could try achieving this with JavaScript by giving each button an individual ID, but there must be a more efficient way using JavaScript.

        <div class="row">
            <div class="col offset-md-2">
                <div class="form-group">
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-secondary" id="zone1">Zone 1</button>
                        <button type="button" class="btn btn-outline-secondary" id="zone2">Zone 2</button>
                        <button type="button" class="btn btn-outline-secondary" id="zone3">Zone 3</button>
                        <button type="button" class="btn btn-outline-secondary" id="zone4">Zone 4</button>
                        <button type="button" class="btn btn-outline-secondary" id="zone5">Zone 5</button>
                        <button type="button" class="btn btn-outline-secondary" id="zone6">Zone 6</button>
                        <button type="button" class="btn btn-outline-secondary" id="bush">Bush</button>
                    </div>      
                </div>
            </div>
        </div>

Answer №1

If you're looking to achieve this functionality using only pure JavaScript, one approach would be to attach a click event handler to each element. This handler would then update the class of the element when the button is clicked:

var buttons = document.getElementsByTagName("button");

for (var i = 0; i < buttons.length; i++) {   

 buttons[i].onclick = function() {
    this.classList.remove('btn-outline-secondary');
    this.classList.add('btn-primary');
 }

}
.btn-outline-secondary {border: 1px solid #aaa;}
.btn-primary {border: 1px solid blue; background: blue; color: white;}
<div class="row">
  <div class="col offset-md-2">
    <div class="form-group">
      <div class="btn-group">
        <button type="button" class="btn btn-outline-secondary" id="zone1">Zone 1</button>
        <button type="button" class="btn btn-outline-secondary" id="zone2">Zone 2</button>
        <button type="button" class="btn btn-outline-secondary" id="zone3">Zone 3</button>
        <button type="button" class="btn btn-outline-secondary" id="zone4">Zone 4</button>
        <button type="button" class="btn btn-outline-secondary" id="zone5">Zone 5</button>
        <button type="button" class="btn btn-outline-secondary" id="zone6">Zone 6</button>
        <button type="button" class="btn btn-outline-secondary" id="bush">Bush</button>
      </div>
    </div>
  </div>
</div>

For additional resources and information on handling events without a framework and manipulating classes of elements, check out these answers.

An alternative method

If you're open to utilizing jQuery or similar libraries, implementing the event handler becomes much simpler. By incorporating the jQuery library into your project, the code could be condensed to:

$("button").click(function(){ /*apply new class using .removeClass() and .addClass() methods*/ });

Refer to jQuery documentation for further insights on the .click() method.

Answer №2

const buttons = document.getElementsByTagName("button");

for (let i = 0; i < buttons.length; i++) {   
 buttons[i].onmouseover = function() {
    this.classList.remove('btn-outline-secondary');
    this.classList.add('btn-primary');
 }
 
 buttons[i].onmouseout = function() {
    this.classList.remove('btn-primary');
    this.classList.add('btn-outline-secondary');
 }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
  <div class="caontainer">
    <div class="row">
      <div class="col offset-md-2">
        <div class="form-group">
          <div class="btn-group">
            <button type="button" class="btn btn-outline-secondary" id="zone1">Zone 1</button>
            <button type="button" class="btn btn-outline-secondary" id="zone2">Zone 2</button>
            <button type="button" class="btn btn-outline-secondary" id="zone3">Zone 3</button>
            <button type="button" class="btn btn-outline-secondary" id="zone4">Zone 4</button>
            <button type="button" class="btn btn-outline-secondary" id="zone5">Zone 5</button>
            <button type="button" class="btn btn-outline-secondary" id="zone6">Zone 6</button>
            <button type="button" class="btn btn-outline-secondary" id="bush">Bush</button>
          </div>      
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Hopefully, this solution helps :)

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

The issue with importing data into Google Sheets due to an error with Ljava

After combining different scripts, I am struggling to properly input data into the code. Email Input: *Status:* *Date:* 03/31/2020 *WorkOrder:* 123456-1 *DMSShipDate:* 03/31/2020 *PONumber:* 8675309 *Company:* Test New Script var ui = SpreadsheetApp.g ...

Steps to fix the error message "Unable to access properties of null (reading 'toLowerCase')"

I encountered an error while working on my React project, and I need assistance to resolve it. The error message is: Cannot read properties of undefined (reading 'toLowerCase') App.js import "./App.css"; import Navbar from "./Com ...

Difficulty in implementing a radio button selection form using Django and Bootstrap styles

Currently, I am facing an issue while trying to develop a form with radio button choices using Django. The website is based on Bootstrap 4 theme and encountering a problem where the buttons disappear upon applying the custom-control-input class. I initial ...

Is utilizing the "sandbox attribute for iframes" a secure practice?

lies an interesting update regarding a technique mentioned in Dean's blog. It seems that the said technique may not work well in Safari based on comments received. Therefore, there is a query about its compatibility with modern browsers, especially Sa ...

I possess a JSON object retrieved from Drafter, and my sole interest lies in extracting the schema from it

Working with node to utilize drafter for generating a json schema for an application brings about too much unnecessary output from drafter. The generated json is extensive, but I only require a small portion of it. Here is the full output: { "element": ...

A glitch in showcasing the hello world example in Node.js with express

I've been diving into learning node.js and I'm eager to use the express framework. However, I hit a roadblock when trying to run a simple "hello world" example from the expressjs.com website. Instead of seeing the expected output, I encountered a ...

Incorporating TWEEN for camera position animations: A complete guide

function adjustCameraPosition(newPosition, animationDuration) { var tween = new TWEEN.Tween( camera.position ) .to( newPosition, animationDuration ) .easing(TWEEN.Easing.Linear.None) .onUpdate(fun ...

React Functional Component fails to update on state changes

I'm in the process of creating a React application where I can input my height and weight to calculate my BMI. The goal is to display the BMI value on a diagram. To keep things organized, I decided to break down the functionality into smaller componen ...

Guide to updating passwords with passport-local-mongoose

After successfully importing the passport-local-mongoose to my code and being able to register and log in users, I now face the challenge of changing the password for a specific user. How can I achieve this? According to the documentation of passport-local ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Siblings are equipped with the advanced selector feature to

I'm struggling to understand this setup I have: <div class="container"> for n = 0 to ... <a href="some url">Link n</a> endfor for each link in ".container" <div class="poptip"></div> ...

Mocha Test Runs Are Exceeding Time Limits

I've updated to Node.js 4.0 which now supports generators. After trying gulp-mocha-co and upgrading to Node 4.0 for generator support, I encountered timeouts in my mocha tests when trying to make them generator-friendly. Adding the * to my mocha unit ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Adding embedded attributes from a different object

I am facing a challenge with two arrays called metaObjects and justObjects. These arrays consist of objects that share a common property called id. My goal is to merge properties from the objects in these separate arrays into a new array. const metaObje ...

Creating a layout with cards positioned next to each other using Bootstrap

I have been trying to display these 3 cards side-by-side, but they always end up stacked on top of each other. Is there a specific code I need to add to fix this? <div class="col-md-4"> <div class="card rounded-lg" style="width: 17.5rem;"> ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

Issue with Node.js MongoDb query results in the retrieval of all documents instead of the specific

Example of Json Structure: {"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bron ...

Having difficulty retrieving keys from a JSON object returned by a mongoose findOne() query

Recently, I've come across a strange issue. I used mongoose to search for a document in my mongoDB using model.findOne() with the following code: Model.findOne({ ID: ID }).then(existingDoc => { console.log(existingDoc ); res. ...

Creating immersive 3D graphics using Three.js

Exploring three.js for the first time and experimenting with displaying a basic 3D model using three js, Vue, and Laravel. The 3D file can be found at /public/files/Tree1.3ds. Need help rendering the file in the Vue component with three js. Initially tried ...

"Enhance Your Website with Custom jQuery Preloaders

Currently, I am facing a challenge while developing a website. Specifically, I am struggling with resolving the issue of a blank page being displayed. The website that I am working on involves functionality where swiping right triggers data insertion into ...