The deletion of columns is malfunctioning when using jQuery

When I click on number 2, it deletes the second column, which is working correctly. However, when I click on number 3, it deletes the number 3 instead of its column. The code snippet causing this issue is shown below:

Can someone assist me in identifying what is wrong here?

$(document).on('click',".button", function( event){
var attrNumColumn = $(this).attr('attrnum');
$(".button[attrnum='"+attrNumColumn+"']").remove();
//console.log($(this).attr('attrnum'));
var attrNumColumnMinus = parseInt($(this).attr('attrnum')-1);
$('tr').each(function(){
$(this).children("td:eq("+attrNumColumnMinus+")").remove();
});
});
.button {
height: 25px;
width: 10px;
}

.button:hover {
color: #c30202;
cursor:pointer;
}
<div class="button" attrnum='1'> 1 </div>
<div class="button" attrnum='2'> 2 </div>
<div class="button" attrnum='3'> 3 </div>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<script   src="https://code.jquery.com/jquery-1.12.4.min.js"   integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="   crossorigin="anonymous"></script>

Answer №1

To find the index of the button and remove the corresponding td element, you can use $(".button").index(this).

Your code has been optimized for efficiency.

$(document).on('click',".button", function( event){
    var number = $(".button").index(this)
    $(this).add("tr td:nth-child(" + (number + 1) + ")").remove() // credit to Endless for this line
});

$(document).on('click', ".button", function(event) {
  var number = $(".button").index(this)
  $(this).add("tr td:nth-child(" + (number + 1) + ")").remove()
});
.button {
  height: 25px;
  width: 10px;
}

.button:hover {
  color: #c30202;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="button" attrnum='1'> 1 </div>
<div class="button" attrnum='2'> 2 </div>
<div class="button" attrnum='3'> 3 </div>

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
  </tr>
</table>

Answer №2

The issue with your function was that it assumed the length of tr would always remain the same regardless of node removal. Therefore, when you remove the second element, the length of the td in tr's becomes 2. As a result, trying to access td[2] on the removal attrnum='3' fails because it is not present. I have made updates to your code, please review it below:

$(document).on('click',".button", function( event){
var attrNumColumn = $(this).attr('attrnum');
$(".button[attrnum='"+attrNumColumn+"']").remove();
//console.log($(this).attr('attrnum'));
$('tr').each(function(){
$(this).children("td[attrnum='"+attrNumColumn+"']").remove();
});
});
.button {
height: 25px;
width: 10px;
}

.button:hover {
color: #c30202;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="button" attrnum='1'> 1 </div>
<div class="button" attrnum='2'> 2 </div>
<div class="button" attrnum='3'> 3 </div>

<table>
  <tr>
    <td attrnum='1'>1</td>
    <td attrnum='2'>2</td>
    <td attrnum='3'>3</td>
  </tr>
  <tr>
    <td attrnum='1'>4</td>
    <td attrnum='2'>5</td>
    <td attrnum='3'>6</td>
  </tr>
  <tr>
    <td attrnum='1'>7</td>
    <td attrnum='2'>8</td>
    <td attrnum='3'>9</td>
  </tr>
</table>

Answer №3

Check out the Javascript snippet below:

    <div class="button" attrnum='1'> 1 </div>
<div class="button" attrnum='2'> 2 </div>
<div class="button" attrnum='3'> 3 </div>

<table>
  <tr>
    <td class="col-1">1</td>
    <td class="col-2">2</td>
    <td class="col-3">3</td>
  </tr>
  <tr>
    <td class="col-1">4</td>
    <td class="col-2">5</td>
    <td class="col-3">6</td>
  </tr>
  <tr>
    <td class="col-1">7</td>
    <td class="col-2">8</td>
    <td class="col-3">9</td>
  </tr>
</table>

$(document).on('click',".button", function( event){
    var attrNumColumn = $(this).attr('attrnum');
  $('.col-'+attrNumColumn).remove();  
});

To see a live example, click here: https://jsfiddle.net/9p77afc3/10/

If you want to remove the number as well, then try this link: https://jsfiddle.net/9p77afc3/11/

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

Using PHP to trigger a simulated click on a div element upon the page being loaded

My goal is to automatically trigger a click on a div element when the page loads and detects 'settings' in the URL using PHP. However, for some reason, this code snippet does not seem to work as expected. if(isset($_GET['settings'])){ ...

Configuring the "trust proxy" setting in Express for Node.js with CloudFront

I am utilizing an Express backend with AWS Cloudfront. How can I properly configure the trust proxy setting for AWS Cloud Front? app.set('trust proxy', function (ip) { if ( ???????????? ) return true; // trusted IPs else return false; }); A ...

Hovering over triggers tooltip flickering with Mouseover/Mouseenter interaction

When the mouseover event is triggered on the parent element, there seems to be a flickering issue when moving into the tooltip (child) element. The console log indicates that the mouseover/mouseenter event is being fired rapidly. The tooltip does not stay ...

Having identical functions with varying IDs and the same variable in Ajax is causing issues

Here, I have two HTML rows with different IDs. When the function ItemSearch() is called, I want to display the search results for both IDs. I am new to JavaScript and AJAX. ***1st Html*** <div class="justlauchSearch"> <div class="input-gro ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

What is the process for converting HTML into XHTML?

I'm looking for the most efficient method to convert HTML documents into valid XML, specifically XHTML. Any recommendations on a toolkit, library, sample, or any other resource that can assist with this task? Just to clarify, my application needs to ...

Having trouble with the sx selector not functioning properly with the Material UI DateTimePicker component

I'm currently working with a DateTimePicker component and I want to customize the color of all the days in the calendar to match the theme color: <DateTimePicker sx={{ "input": { color: "primary.main&quo ...

Creating a visually appealing user interface can be achieved by utilizing HTML/CSS to include bullet points and enumeration numbers in the page

I am looking for a way to display lists in a document with a style similar to the image on the right below: The text content of the list items is formatted like any other <p> and the bullet points are located in the margin. Is there a CSS solution ...

Discovering the connection details between two datasets: nodejs and mongodb

I am working with 2 schemas (event and venue). Below is the Event Schema: var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var EventSchema = mongoose.Schema({ _id:mongoose.Schema.Types.ObjectId, name:{type:Stri ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Tips for extracting information from a website that uses Javascript with Python?

I am currently working on a web scraping project to extract data from the DoorDash website specifically for restaurants located in Chicago. The goal is to gather information about all the restaurant listings in the city, such as reviews, ratings, cuisine, ...

How can I extract and display data from a MySQL database in cytoscape.js?

I have a database table called 'entrezgene' that contains geneID and name fields. These fields will be used to create nodes in cytoscape.js. Additionally, I have another table named 'interaction' with geneID and geneID2 fields, which wi ...

Changing fonts for languages that are read from right to left in WordPress

I am currently working on a WordPress site that features posts in both English and Urdu. The English posts are written from left to right (ltr), while the Urdu posts are written from right to left (rtl). When I submit post data in the wp editor, it publish ...

Managing data that is not defined in ajax requests

When working with my ajax call, I have encountered an issue where the request stops the page from loading due to undefined data being passed. I am wondering if there is a way to implement a condition that can handle requests with undefined values? Would ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

Leveraging the Jpeg-autorotate npm package to automatically adjust image orientation according to EXIF data in JavaScript

Struggling with an issue in my web app where uploaded images display sideways, I decided to utilize this module to rotate images based on the EXIF data. Here's a snippet of my code: <template> <div :class="$style.form247"> <Can ...

Binding ngModel to a method within $scope in Angular

Not really a question with code, but more for my clarification. Please excuse me if this isn't the appropriate place to ask... I was experimenting with a basic checkbox that had an ngModel assigned to it: <input type="checkbox" ng-model="someFlag ...

"Concealing sibling sections on the same level with JQuery - a helpful guide

As someone who primarily works on backend development, I am fairly new to JQuery. Currently, I have a specific table structure that looks like this: <tr> <td> <div class="div-package-service"><a style="cursor: pointer" id="service ...

Personalizing Tooltip Component while Hovering on React AG Grid Table (v 18 beta)

I am currently working on a project involving a react ag grid table that is using an older version (18 beta). Due to specific requirements and existing functionality constraints, I am unable to update or migrate to newer versions. As a result, I am looking ...

The value retrieved by JQuery attr remains constant

Hey everyone, I'm having an issue with getting the ID from a custom attribute using jQuery. When I try to debug, I keep getting the same value each time. I have an HTML table that lists posts from a database using PHP, each with its own specific ID. ...