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

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

Updating the text box's font color to its original black shade

I have a form that includes dynamic text boxes fetching data from the backend. When a user clicks on a text box, the color of the text changes. Upon form submission, a confirmation message is displayed and I want the text box color to revert back to black. ...

Using ASCII 3D text can create a stunning visual effect on a website, but it can sometimes appear

My website is displaying ASCII 3D Text with glitchy lines, but this issue is not present on other websites. Example 1: Glitchy lines visible on my website Example 2: A different website using the same text without any glitchy lines. No glitches detected h ...

An issue has occurred: TypeError - It is impossible to access the 'forEach' property of an undefined object

Having trouble with a promise issue that I just can't seem to solve. Whenever I enter 'pizza' into the search bar and click search, the console displays an error message: TypeError: Cannot read property 'forEach' of undefined I&ap ...

Contrast between the functionalities of $.ajax and $.post

$.post( url, data, callback, type ); $.ajax () Is there a distinction between using $.post and $.ajax in jQuery? And if so, which method is recommended? Also, how many parameters can be passed to the $.ajax function? ...

Increase transparency of scrollbar background

Is it possible to adjust the opacity of a scrollbar track? I attempted to use opacity:0.5, but it didn't have any effect. I am using material UI styled, although I don't believe that is causing the issue. const Root = styled('div')(({ ...

Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId var array = [ { id: 10, unitId: 'unit17' }, { id: 11, unitId: 'unit19' }, { id: 13, unitId: 'unit27' }, { id: 12, unitId: 'unit2' }, { id: 13, unitId: 'unit ...

Using information retrieved from a JSON response

In my current project, I have set up a JavaScript object within a script tag. <script> searchdata = {"employees":[{"name":"john doe","sal": "10000"}]}; </script> I am utilizing the searchdata object in various functions as shown below: fu ...

Utilize Bootstrap to position the button right next to the input field

I am having trouble aligning the button on the right next to the email textbox. Unfortunately, my attempts have not been successful. Fiddler: https://jsfiddle.net/Vimalan/mt30tfpv/4/ <div class="col-xs-3"> <div class="fo ...

Obtain a multiline match using regular expressions

Is there a way to use regex to match only multi-line strings without matching single-line strings as well? Here is the current regex I am using: Regex ('|"|`)[\s\S]*?(\1) Test string "not a match" "need to match&qu ...

Ways to implement border spacing using CSS

Here's a snippet of the code I've been working on: HTML: <html> <body> <div id="article"> <h1>TITLE</h1> <p>text</p> </div> </body> </html> CSS: #article { colo ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Press the designated button located within a table's td element to retrieve the values of adjacent td elements

I need to implement a functionality where clicking a button within a <td> element will retrieve the values of other <td> elements within the same row (<tr>). Here is the current implementation: $(document).ready(function(){ ...

Submitting an AJAX request to upload an XML file and an image file simultaneously in one call

I need to send both an uploaded image and an uploaded XML file to a PHP file using a single AJAX call. I have tried using two form data instances, but I am not sure if this is the correct approach. <input type="file" class="form-control-file" name="fil ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

Using Ember's transitionTo method and setting a controller attribute within a callback

I am working with Ember code to transition to a specific route while also setting controllerAttr1 on 'my.route' Upon transitioning to "my.route" using this.get('router').transitionTo("my.route"), I have set up a callback function that ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Execute scroll to top animation but without utilizing $('html,body').animate({scrollTop: 0}, 'slow')

As someone who is just starting to explore jQuery, I hope you can bear with me. I've implemented this styling: html, body{ height: 100%; overflow: auto; } Along with this script: $(document).ready(function() { $('#guide-wrap'). ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...