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

Scrolling smoothly and triggering a function when a button is clicked

import React, { useState, useRef } from "react"; import { Link, animateScroll as scroll } from "react-scroll"; function Accordion(props) { const contentRef = useRef(null); const [activeClass, setActiveClass] = useState("" ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Refresh the DIV element that houses dynamically generated <ul> HTML content after submitting new inputs

UPDATE: After delving into the code of nested include files in the child PHP file, I've identified conflicts with the parent PHP include files. This means that the child PHP file/div relies on the parent being refreshed, preventing me from refreshing ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

Having trouble displaying database model information in the template

My challenge is displaying information from the Django third model (class Jenkinsjobsinformation) in the template. I've been successful in showcasing data from the first and second models (Projectname and Jenkinsjobsname). See below for a snippet of m ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...

Looking to showcase the outcome of the Procedure invocation when I made the call?

{ "isSuccessful": true, "resultSet": [ { "name": "pradeep", "password": 123, "timestamp": "2014-04-08T12:58:45.000Z" }, { "name": "dileep", "password": 1234, "timestamp": "2014-04-08T13:00:52.000Z" } ] } I have ...

Steer clear of dividing words

I am attempting to showcase sentences letter by letter with a fade in/fade out effect. However, I am facing an issue where words break in the middle. How can this word breaking be prevented? var quotes = document.getElementsByClassName('quote' ...

Issue with EaselJS: mouse events are no longer functional

I'm currently working on adding a touch animation using the EaselJs library. Interestingly, when I load an image from a local folder, all mouse events work as expected, such as onPress. However, things take a different turn when I opt to use an imag ...

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

Action of Submit Button Based on Field Matching Another Form

I currently have a single page that contains two forms, with only one form being displayed at the moment. The concept is that if the user selects a specific state from the drop-down menu and clicks on the submit button, they will be redirected to either a ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

Ways to eliminate the navigation button on an HTML5 video player

I'm having a great experience using the HTML5 video player to continuously play videos. However, I have noticed that when my mouse cursor hovers over the video, a navigation button appears at the end of the screen. I would like to either remove or hid ...

What is the best way to position four circles within a square container using CSS?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .circles { height: 150px; width: 150px; background-color: #bbb; border-radius: 50%; displ ...

The click event in jQuery/JavaScript is not functioning

Although it should be as simple as breathing, I just can't seem to spot the mistake in my code... I attempted to add a click event to a div with a unique ID, but unfortunately, it's not working at all. This issue persists with both jQuery and Ja ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

How can we determine the dimensions of an absolutely positioned element within a relatively positioned element?

One thing I noticed is that when placing an absolutely positioned element within a relatively positioned element, the latter does not automatically inherit the width and height of the former unless manually set. Take this example: <!DOCTYPE html> ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...