Stopping prior entries in html tables

Is there a way to change the color of samples by clicking on each cell? Additionally, is it possible to cancel previous input by clicking a cancel button? If anyone has experience with this issue, please share your knowledge. Thank you.

$(function() {
  $("td").click(function() {
    $(this).addClass("red");
  });
});
.red{
  background-color: red;
}


td {
  padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
  <td id="9">9</td>
  <td id="10">10</td>
</table>

<button>cancel</button>

Answer №1

Here is the solution:

$(function() {
  let selected = [];
  $("td").click(function() {
    let selectedID = $(this).attr('id');
    selected.push(selectedID);
    $(this).addClass("highlight");
  });
  $("#btnCancel").on('click',() => {
    if(selected.length) {
      let lastSelected = selected.pop();
      $(`td#${lastSelected}`).removeClass("highlight");
    }
  })
});
.highlight{
  background-color: yellow;
}

td {
  padding: 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
  <td id="9">9</td>
  <td id="10">10</td>
</table>

<button id="btnCancel">cancel selection</button>

Answer №2


    let currentElement = null;
    $(function() {
      $("td").click(function() {
        $(this).addClass("highlighted");
        currentElement = $(this);
      });

      $('button').click(function() {
        if (currentElement !== null)
          currentElement.removeClass('highlighted');
      });
    });
  

Answer №3

To keep track of the history, you can follow these steps:

const visitedPages = [];

function addToHistory(page) {
  const index = page.target.id;
  if (visitedPages.indexOf(index) < 0) visitedPages.push(index);
  highlight();
}

function undo() {
  visitedPages.pop();
  highlight();
}

function highlight() {
  const elements = document.getElementsByTagName("td");
  for (let i = 0; i < elements.length; i++) {
    elements[i].classList.remove("red");
  }
  visitedPages.forEach(index => {
    document.getElementById(index).className = "red";
  });
}
.red{
  background-color: red;
}


td {
  padding: 5px
}
<table>
  <td onclick="addToHistory(event)" id="1">1</td>
  <td onclick="addToHistory(event)" id="2">2</td>
  <td onclick="addToHistory(event)" id="3">3</td>
  <td onclick="addToHistory(event)" id="4">4</td>
  <td onclick="addToHistory(event)" id="5">5</td>
  <td onclick="addToHistory(event)" id="6">6</td>
  <td onclick="addToHistory(event)" id="7">7</td>
  <td onclick="addToHistory(event)" id="8">8</td>
  <td onclick="addToHistory(event)" id="9">9</td>
  <td onclick="addToHistory(event)" id="10">10</td>
</table>

<button onclick="undo()">Reset</button>

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

Adjust the vertical positioning according to the percentage of the width

Currently, I am attempting to modify the position of my navigation bar on the screen in relation to the screen width rather than the height. I previously attempted using top: 10% in CSS, but realized this is based on the screen's height instead of its ...

Discover the step-by-step guide for inserting personalized HTML into the current widget screen on Odoo 12 with

For the past 3 days, I've been stuck trying to figure out how to print order items. My goal is to have a custom HTML code added to a div with the class 'order-print' when the Order button is clicked. I am using odoo 12 and facing issues wit ...

Creating a new version of the Javascript prompt() dialog by incorporating a modal interface

My current assignment involves replacing a JavaScript prompt call with a unique custom function that utilizes a stylish JavaScript-activated modal dialog. This particular function is only called once and anticipates receiving a string input from the user. ...

Leveraging jQuery to automatically fill in a time field while excluding other buttons

I've been working on using jQuery to automatically fill in a time input field. The functionality is working properly, but the time is also being applied to my other button. How can I make sure it only gets assigned to the time input field? I would re ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

Angular SPA Routing for .Net Core 2.0

Having recently created a new Angular SPA project using the .Net core 2.0 SPA templates, I find myself facing some challenges as a newcomer to Angular/Typescript and HMR. While most functionalities were working smoothly at first, I noticed a peculiar issu ...

Comparing XDomainRequest and XMLHTTPRequest - which one to choose

Our team is currently developing an application utilizing PixiJS that integrates a dynamic json loader. The .json files are loaded using the following logic: if(window.XDomainRequest) { this.ajaxRequest = new window.XDomainRequest(); } else if (windo ...

When an icon is hovered over in Vue, a text box popup will be displayed

Working on a personal project that requires obtaining the status of all devices within a unit. The status, along with the device name, is returned in an array from the function deviceStatus(). If all devices are currently marked as ON, the home icon next t ...

JavaScript Mortgage Calculator: Issue with Input Field Formatting when Adding Commas

I am currently developing a mortgage calculator and I would like to include commas in the form fields. The code I found worked well initially, but once numbers reached over 1,000,000, the formatting became strange. Since I am new to JavaScript, any guidanc ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

I need to display a VARCHAR variable retrieved from PHP in a visually appealing way with HTML/CSS. What is the best way to automatically format it to prevent it from appearing as one long, uninterrupted sentence?

Is there a way to automatically format the text retrieved from a VARCHAR variable in a MySQL database via PHP so that it displays correctly with line breaks? Currently, when I display it on an HTML page, it appears as one long string. I've considered ...

React, Redux, Thunk - the trifecta of powerful

After spending a considerable amount of time struggling with this particular piece of code, I have scoured online resources such as Stack Overflow and the documentation, but there is still something that eludes me... The code in question revolves around t ...

Submitting identical named elements in MVC4 can be achieved by utilizing the proper syntax and techniques

I have two elements with the same name. One is created before dynamically and the other after being created dynamically. Element created before dynamically - <input id="txtamt" name="Amount[]" type="text" ></td> Element created after dynami ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Having trouble with the linear gradient color length in HTML?

I'm attempting to design a gradient background using HTML and CSS. The gradient I want should be red for the top 10% and green for the remaining 80%, similar to this example: https://i.sstatic.net/TlnIh.jpg To achieve this, I came up with the follo ...

Creating a pros and cons form for users using jQuery involves dynamically checking and updating the input values to ensure that no

When a new value is entered into the input box in this code, it will add and replace it for all P's tag. The desired change is to create a div with .pros-print class after each other, where the content of the P tags is equal to the new input value whe ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

At times, Chrome fails to load CSS files when requested

Whenever I visit this ASPX page, the stylesheets sometimes fail to load. There is no request made and even checking the network log in Chrome's debugger confirms that it didn't request or load from cache. Interestingly, all other resources such a ...

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...

Utilizing Firebase authentication and next-auth in Next.js - Authentication currently returns null

I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase Here is the fireba ...