Applying a variety of elements to a single function

I am in the process of creating a mini-survey and I want the buttons to change color when clicked, but return to normal when another button is selected within the same question. Currently, clicking on a button turns it red while leaving the others clear. However, selecting any other button, whether in the current question or the next, resets all buttons to their original state. As a beginner, I would greatly appreciate a clear explanation.

function updateButtonColor(id) {
  var buttons = document.getElementsByClassName('btn');
  for (var i = 0; i < buttons.length; ++i) {
    var item = buttons[i];
    item.style.backgroundColor = (item.id == id) ? "red" : "";
  }
}
.btn {
  width: 100%;
  height: 100%;
}
<div class="background1 ">
  <div class="transbox ">
    <h3 align="center ">Question 1: Disagreeing with a friend on preferences</h3>
    <table border="1 ">
    </table>
    <table id="table1 ">
    </table>
    <table align="center ">
      <tbody>
        <tr>
          <td><input type="button " value="Not at all likely " button id="tab1 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Slightly likely " button id="tab2 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Somewhat likely " button id="tab3 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Moderately Unlikely " button id="tab4 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Likely " button id="tab5 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Very likely " button id="tab6 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Extremely Likely " button id="tab7 " class="btn " onClick="updateButtonColor(this.id) "></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


<div class="background2 ">
  <div class="transbox ">
    <h3 align="center ">Question 2: Betting a day's income on horse racing.</h3>
    <table border="1 ">
    </table>
    <table align="center ">
      <tbody>
        <tr>
          <td><input type="button " value="Not at all likely " button id="tab8 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Slightly likely " button id="tab9 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Somewhat likely " button id="tab10 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Moderately Unlikely " button id="tab11 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Likely " button id="tab12 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Very likely " button id="tab13 " class="btn " onClick="updateButtonColor(this.id) "></td>
          <td><input type="button " value="Extremely Likely " button id="tab14 " class="btn " onClick="updateButtonColor(this.id) "></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Answer №1

Do not iterate through every element with the btn class. Locate the table that contains the current button and only iterate through the buttons within that table.

Additionally, instead of passing this.id to the function, simply pass this.

function modifyColor(button) {
  var table = button.parentElement.parentElement.parentElement;
  var tabs = table.querySelectorAll(".btn");
  for (var i = 0; i < tabs.length; ++i) {
    var item = tabs[i];
    item.style.backgroundColor = (item == button) ? "red" : "";
  }
}
.btn {
  width: 100%;
  height: 100%;
}
<div class="background1 ">
  <div class="transbox ">
    <h3 align="center ">Q1. Disagreeing with a friend on preferences.</h3>
    <table border="1 ">
    </table>
    <table id="table1 ">
    </table>
    <table align="center ">
      <tbody>
        <tr>
          <td><input type="button " value="Not at all likely " button id="tab1 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Slightly likely " button id="tab2 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Somewhat likely " button id="tab3 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Moderately Unlikely " button id="tab4 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Likely " button id="tab5 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Very likely " button id="tab6 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Extremely Likely " button id="tab7 " class="btn " onClick="modifyColor(this) "></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


<div class="background2 ">
  <div class="transbox ">
    <h3 align="center ">Q2. Betting a day's income on horse racing.</h3>
    <table border="1 ">
    </table>
    <table align="center ">
      <tbody>
        <tr>
          <td><input type="button " value="Not at all likely " button id="tab8 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Slightly likely " button id="tab9 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Somewhat likely " button id="tab10 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Moderately Unlikely " button id="tab11 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Likely " button id="tab12 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Very likely " button id="tab13 " class="btn " onClick="modifyColor(this) "></td>
          <td><input type="button " value="Extremely Likely " button id="tab14 " class="btn " onClick="modifyColor(this) "></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Answer №2

The issue you're facing is that all buttons are labeled with the class name "btn".

One solution is to assign specific class names to the inputs based on their corresponding tables and set up an onclick event programmatically. For a demonstration, refer to this Fiddle

Below is the JavaScript code I utilized:

var allButtons = document.getElementsByClassName("btn");

for (var j = 0; j < allButtons.length; j++) {
  var button = allButtons[j];
  button.onclick = function() {

    if (this.classList.contains('q1Button')) {
      var q1Btns = document.getElementsByClassName('q1Button')
      for (var k = 0; k < q1Btns.length; ++k) {
        var item = q1Btns[k];
        item.style.backgroundColor = (item.id == this.id) ? "red" : "";
      }
    }

    if (this.classList.contains('q2Button')) {
      var q2Btns = document.getElementsByClassName('q2Button')
      for (var k = 0; k < q2Btns.length; ++k) {
        var item = q2Btns[k];
        item.style.backgroundColor = (item.id == this.id) ? "red" : "";
      }
    } 

  }
}

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

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Dynamic scrolling feature for lists that moves horizontally

When working with a lengthy list, I encountered an issue with horizontal scrolling. It worked fine when the list was statically implemented as shown below. <div style="margin-top:100px;white-space: nowrap;"> <ul > <li style= ...

the button function is unresponsive

Can someone please help me troubleshoot my jQuery code? Everything seems fine, but the generate button is not working when clicked! PS: I've searched extensively for a solution to this problem but haven't been able to find one. I've also at ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Create HTML files that generate a log.txt document

It seems like every time I try to find a solution for writing files with PHP or JavaScript, I end up in a never-ending argument. Some say it's impossible, while others claim it's possible under certain conditions. Unfortunately, none of the code ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

User class instantiation in livequery is initiated

Is it possible to initialize the user class in a live query? I have initialized the user class in my index.js and it shows up in my network inspector. However, when I attempt to query, nothing appears in the websocket. Below is the code showing how I init ...

Updating state within a loop of properties in a React ComponentDidUpdate function

I have been working on a project where I needed to update the state after the componentDidMount lifecycle method. The props that I am expecting in the child component are only available at mount, so I can only update the state after that point. The only so ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Test the file upload functionality of a Node Js application by simulating the process using Chai

My API testing involves receiving a file as input. I have successfully used the attach() function for this purpose. To cover all scenarios, I anticipate using around 20 different input files. Rather than storing these 20 files individually, my idea is to c ...

What is the method for changing the icon color to dark in Twitter Bootstrap?

I am facing an issue where the icon in my menu tab turns white when active, making it difficult to see. Is there a way to change the color of the icon to black? I have found a class icon-white to make it white, but there is no corresponding class to make ...

Issue with Angular ngFor binding. What could be causing this error to occur?

I have a main component called DOCUMENT. This document receives a URL segment and retrieves an array of associated objects from my database. Then, using @Output() documents = new EventEmitter() and an @Input() in a DOCUMENT VIEW component, I loop through t ...

The POST request did not yield an HttpResponse object; instead, it returned None

When I submit a selection from a dropdown form to views as a POST request, and then use this selection to query data from Django, I encounter an issue while trying to map Django models data to Highcharts following this approach. The error message "the view ...

Puzzled by the CSS Box Model - There's a piece of the puzzle I

Check out my simplified fluid layout right here at this link. I've been trying to figure out why the alignment between the right column and the header above it seems off, even though there's no padding involved. Both have the same border styles, ...

Is there a way to successfully implement this CSS animation utilizing background images in a Markdown document?

I am attempting to create a dynamic animation on a <canvas> element by changing the background image using the @keyframes rule in CSS. Unfortunately, I am facing difficulty getting the animation to work. The <canvas> tag does not even display a ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Image element for Material UI CardMedia

There is a component in Material UI called CardMedia that allows for media content within a Card. The Mui website showcases an example using the img tag with CardMedia. https://mui.com/material-ui/react-card/#complex-interaction I am interested in using ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

Removing an embedded document from an array in MongoDB using Mongoose when the document's status is set to false

I am in desperate need of a solution for this mongoose-related issue. My tech stack includes Express, Mongoose, and GraphQL. To give you some context, I have two collections: users and groups. user { name: string, groupAsMember: [groups], status: bo ...