Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below:

https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/

I need help with creating a remove function and adding a CSS class to a clicked row.

1. When I click on "remove", the clicked row should be deleted.

  1. When I click on a row, it should be highlighted with a 'highlightRow' CSS class

  2. I also need to check if there are any rows in the table and store that information in a variable

  3. Only one row at a time should be highlighted in red (clicked row). If no row is selected, the remove button should not be visible

HTML

col1header col2header

CSS


.visibilityHide {
    visibility: hidden;
}
.highlightRow{
  color:red;
}
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}

JS or Jquery


function add() {
  var addRow1;
  var addRow2;
  addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
  addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
  $("#myTableid tbody").append(addRow1);
  $("#myTableid tbody").append(addRow2);
}

function remove() {

}

function getdetails(row) {
  $('#removerow').css('visibility', 'visible');
}

Answer №1

Here is the updated javascript snippet that fulfills all your requirements.

function add()
{
    var addRow1;
    var addRow2;
    addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
    addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
    $("#myTableid tbody").append(addRow1);
    $("#myTableid tbody").append(addRow2);

}


function remove()
{
    $(".highlightRow").remove();
    $('#removerow').addClass('visibilityHide');
    $("#dropDown").prop("disabled", $("#myTableid tbody tr").length > 0);
}

function getdetails(row)
{
    $('#removerow').toggleClass('visibilityHide', $("#myTableid tbody tr").length === 0);
    $(".highlightRow").removeClass("highlightRow");
    $(row).addClass("highlightRow");
}

Answer №2

Give this a try and see if it works:

function add(){
  var addRow1;
  var addRow2;
  addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
  addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
  $("#myTableid tbody").append(addRow1);
  $("#myTableid tbody").append(addRow2);
}


function remove(){
  $('.removeClass').remove(); //remove clicked row
  if($('table tbody tr').length <=0){
    $('#removerow').hide();
  }
  if($('table tbody tr').length===0) {
    alert('This last child has been removed');
    $("#dropDown").prop("disabled", false);
  }
}

function getdetails(row){
  $('#removerow').show();
  $(row).addClass('removeClass'); //add class on clicked row
}
.highlightRow{
  color:red;
}
table {
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid black;
}
.removeClass{
  color:red;
}
#removerow {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTableid">
<thead>
  <th>
    col1header
  </th>
  <th>
    col2header
  </th>
</thead>
<tbody>
  
</tbody>
</table>

<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />

To determine if the row is the last one, check this part of the code:

if($('table tbody tr').length==0) {
    alert('This last child has been removed');
    $("#dropDown").prop("disabled", false);
}

Answer №3

Follow the steps below for all the solutions you need: -

function add(){
  var addRow1;
  var addRow2;
  addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
  addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
  $("#myTableid tbody").append(addRow1);
  $("#myTableid tbody").append(addRow2);
}


function remove(){
  var index = parseInt($('.removeClass').index())+1;
  $('.removeClass').remove(); //remove clicked row
  $('.removed_row').html("<strong>row number "+index+ " removed</strong>");
  if($('table tbody tr').length <=0){
    $('#removerow').hide();
  }
}

function getdetails(row){
  $('#removerow').css('display', 'block');
  $('.removeClass').removeClass('removeClass');
  $(row).addClass('removeClass'); //add class on clicked row
}
.visibilityHide {
  display: none;
}
.highlightRow{
  color:red;
}
table {
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid black;
}
/* style added for a different look when the class is added */
.removeClass{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTableid">
<thead>
  <th>
    col1header
  </th>
  <th>
    col2header
  </th>
</thead>
<tbody>
  
</tbody>
</table>

<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />

<br>
<br>
<br>

<div class="removed_row"></div>

Answer №4

To see the solution, please refer to my latest update:

const remove = () => {
   window.selectedRow.remove();
   $('#removerow').css('visibility', 'hidden');
}

const getDetails = (row) => {
    removeHighlights();
    window.selectedRow = row;
    row.classList.add("highlightRow");
    $('#removerow').css('visibility', 'visible');
}

const removeHighlights = () => {
    const elements = document.getElementsByClassName("highlightRow");
    while(elements.length > 0){
        elements[0].classList.remove('highlightRow');
    }
}

https://jsfiddle.net/g63zpuuz/

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

What is the functionality of the post method in PHP?

Is there a solution to this issue? //error_reporting(0); $token = $_POST['token']; $invite = $_POST['invite']; $url = "https://mywebsite.com/asd/".$invite.""; $dingaling = "$token" ?> When: ERROR: Notice: Undefined index: token ...

padding applied exclusively to the Bootstrap column when viewed on a large grid

Can padding be added only for the large grid and not for the medium grid? Large grid with padding: <div class="col-lg-4 pl-3"> </div> Medium grid without padding: <div class="col-md-3"> </div> ...

Are DOM Events compatible with ajax-loaded content that cannot be unloaded?

How should events be managed with ajax-loaded content that can be hidden or displayed? I have created a sidebar in HTML that toggles visibility on click, along with two pages that are loaded using ajax. When the sidebar is hidden or displayed, I need to ...

Asp.Net Core Ajax issue: Pagnation not refreshing the target

This is a straightforward issue! My partial loads correctly using ajax to apply filters and sorting. However, the pagination links send the correct URL, and the response is the desired page but it doesn't update or replace what's currently displa ...

How come my Bootstrap container columns are not remaining evenly divided into four parts?

Struggling to split a section of my project into 4 equal parts using the bootstrap col attribute. Unfortunately, every time I try, the last container ends up breaking and shifting below the other 3, creating an unsightly code layout. index.html <sec ...

The firebase collection's model doesn't include an add function within its nested collection

I'm currently developing an application where I aim to utilize Firebase for real-time data storage within the context of the Backbone framework. The issue I am facing is as follows: I have a sub-level model and collection, both of which are standar ...

Understanding page navigation in PHP

Is there a way to validate the inputs on a given page, display error messages if any, and then move to the next page if the inputs are correct? How can this be achieved? <html> <head></head> <body> <?php // define variables an ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Accessing JSON data model from Ember route or controller

Exploring the capabilities of Ember.js Is it possible to expose my data model as JSON through a route or controller? The object saved in the store looks like this: this.store.createRecord('Person', { id: 1, name: this.get('name'), ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

I can't seem to get the dropdown list to appear. What could be the issue?

I'm currently trying to create a pure CSS dropdown menu on hover by following this tutorial. However, despite multiple attempts, I'm still stuck and in need of some clear explanations for my issue. <div class="navbar"> ...

Utilize jQuery to toggle classes on and off for anchor elements within list items in an unordered

<ul class="tab_sublinks"> <li><a href="#" class="active">Product Master</a></li> <li style="margin: 0;">|</li> <li><a href="#">Charges Computation Master</a></li> </ul> Ho ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Issue with ISO-8859-1 character encoding in table formatting

I have set my website to use ISO-8859-1 encoding and special characters are displaying correctly. However, I'm facing an issue with the datatables plugin which does not seem to recognize special characters in the table data. Do I need to configure an ...

Utilize Ajax and Nodejs to inject dynamic content into your webpage

Seeking assistance in implementing a project where a navigation bar on the page contains various items, and I aim to display the content of each tab without reloading the entire page. Utilizing Nodejs with the ejs template engine, my research hasn't l ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

The SVG syntax underwent alterations following its transmission via email

Can someone please help me fix this code? My visual studio code interpreter seems to be having trouble recognizing the style code within it. <?xml version="1.0" encoding="utf-8"?> <!-- (c) ammap.com | SVG weather icons --> <svg vers ...

Spread out the items within an inline block

Is there a way to create space between icons that are in an inline block without them touching each other? One solution could be to add a container around each icon, center the icons within the containers, and then place the containers in the block. You c ...

issue with the submit button due to non-functional base64 encoded image

After successfully converting multiple file images to base64 format, I encountered an issue when trying to submit the values. When a user selects multiple images and clicks the submit button, the converted base64 values are returned as undefined. How can t ...