Remove checked rows in a table with a single click

I have created a table with a list and checkboxes next to each element. There is also a Delete button that I want to connect to the delete operation.

Here is the code for the Delete button:

<tr id="deleteproject" >
                        <td width="180" align="center" background="ButtonBackground.png"
onclick = "deleteRow('plist')">
                            <style="text-decoration:none; display:block; width:100%; 

height:100%">
                                <font size="0.5px"><br/></font>
                                <font id="DeleteProject" face="verdana" color="white">
DELETE</font>
                            </a>
                        </td>
</tr>

The table:

<table ID="plist" border="0" cellpadding="0" cellspacing="0" datasrc="#clicklist"
                        style="WIDTH: 380px">
                        <tr>
                            <td id="projline" width="100%" align="left" valign="middle"
 style="margin-left: 16px;">
                                <input type="checkbox" name="AAA"/>
                                <font size="3" face="Arial">
                                    <a id="proj" href="urn:a">
                                        <span datafld="Name" 

style="margin-left: 20px; line-height: 26px;"></span>
                                    </a>
                                </font>
                            </td>
                        </tr>
                    </table>

Function in JS for deleting rows:

function deleteRow(tableID) {
      try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;

        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked)
            {
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
        }catch(e)
{
            alert(e);
        }
    }

When selecting a checkbox and clicking the delete button, an object error occurs which indicates an issue with the JS code.

Answer №1

In order to proceed, you must first create a properly structured table. The current layout is considered invalid for both HTML5 and HTML4 standards. Specifically, the button element should be nested within a table structure. For more detailed information on this topic, please refer to this informative article.

Upon selecting a checkbox from a row and attempting to delete it using the designated button, an object error is encountered. This typically indicates that there is a null reference or an issue with understanding the JavaScript code.

If you are unsure where to begin troubleshooting, start by examining the JS code. It appears that you are attempting to target rows by referencing them as the TableRow Object? or ChildNode?. The ambiguous error message suggests that the DOM elements need to be referenced as objects. There are different methods to achieve this based on your specific situation:

  • The tr elements should be targeted based on their tag name: <tr>.

    • var All_TR_Tags =

      document.getElementsByTagName('tr');

    • Now All_TR_Tags represents an array-like object

We encourage you to review the provided demo and ask questions to clarify any doubts. Generating a comprehensive list of issues and potential fixes would be a time-consuming task. Please note that the styling in the demo is incidental and mainly follows a default template for tables. While JavaScript plays a crucial role, don't overlook the importance of the table structure. The source code has been extensively annotated to aid in your understanding. Feel free to reach out if you require further assistance.

Snippet

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>delRows</title>
  <style>
    .x th {
      color: #FFF;
      background: #2C7EDB;
      padding: 10px;
      text-align: center;
      vertical-align: middle;
    }
    .x tr:nth-child(odd) {
      background-color: #333;
      color: #FFF;
    }
    .x tr:nth-child(even) {
      background-color: #D3E9FF;
      color: #333;
    }
    .x td {
      border-style: solid;
      border-width: 1px;
      border-color: #264D73;
      padding: 5px;
      text-align: left;
      vertical-align: top;
      position: relative;
    }
    .x thead th:first-child {
      border-top-left-radius: 6px;
    }
    .x thead th:last-child {
      border-top-right-radius: 6px;
    }
    .x tbody tr:last-child th:first-child {
      border-bottom-left-radius: 6px;
    }
    .x tbody tr:last-child td:last-child {
      border-bottom-right-radius: 6px;
    }
    th {
      width: 30%;
    }
    th:first-of-type {
      width: 10%;
    }
    table {
      width: 80%;
    }
  </style>
</head>

<body>
  <table id="T1" class="x">
    <thead>
      <tr>
        <th>
          <input id="btn1" type="button" value="DelRows" onclick="delRows('T1')" )/>
        </th>
        <th>A</th>
        <th>B</th>
        <th>C</th>
      </tr>
    </thead>
    <tbody>
      [Table content omitted for brevity]
    </tbody>
  </table>
  <script>
    [JavaScript function delRows() code omitted for brevity]
  </script>
</body>

</html>

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

core.js encountered an issue at line 6210: TypeError - The function this.service.addDepartment does not exist

Whenever I attempt to click the 'Add' button on a web application that I'm constructing, an error pops up. core.js:6210 ERROR TypeError: this.service.addDepartment is not a function at AddEditDepComponent.addDepartment (add-edit-dep.componen ...

jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

The dropdown login form is malfunctioning on my Wordpress website

After reading various tutorials and guides online, I managed to set up a login screen. You can view the code in my jsfiddle: Jsfiddle. Unfortunately, I am facing issues with making the code function correctly. Being new to Jquery, I might have made a begin ...

Tips for extracting the chosen text during a 'change' event

I need to access the text of the currently selected object. When I use $(this).text(), I end up getting all available selections I have attempted the following methods without achieving the desired result: $(this).text() $(this).selected() $(this).se ...

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...

Delay in loading Jquery accordion due to value binding

I've noticed that my jquery accordion takes a significant amount of time to collapse when the page initially loads. After some investigation, I realized that the issue lies in the fact that there are numerous multiselect listboxes within the accordio ...

Retrieve information from the selected row within a table by pressing the Enter key

I have a search box that dynamically populates a table. I am using arrow keys to navigate through the rows in the table. When I press the enter key, I want to retrieve the data from the selected row. For example, in the code snippet below, I am trying to ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

AngularJS - Textarea not resetting content on ng-click event

Having an issue with my textarea. When attempting to clear it using ng-click, nothing happens... Can anyone provide assistance? Here is my code for testing: My app If you prefer to view it here: HTML : <div ng-controller="Ctrl1"> <d ...

Streamlining the process of formatting URLs?

I was pondering if there is a more efficient method to accomplish this task. I extract links from a webpage, but many of them are relative. for example /index.html for instance /home.index.html Currently, my approach involves adding the home URL to compe ...

Stop HTML audio playback upon clicking on a specific element

I'm looking to add background music to my website with a twist - a music video that pops up when the play button is clicked. But, I need help figuring out how to pause the background music once the user hits play. Play Button HTML - The play button t ...

Question about React.js: What is the best way to add multiple classes to a component by using a ternary operator?

I am looking to apply multiple classes to a component by utilizing a ternary operator. In our shared ts theme file, we have the general button styles defined, but for this specific component, I want to adjust the sizes based on screen width. To achieve thi ...

Material UI - Utilizing multiple CSS classes within a unified global theme

Exploring the world of Material UI within React for the first time has been an exciting journey. I am currently looking to customize my global theme, specifically targeting two classes: .MuiListItem-root.Mui-selected, .MuiListItem-root.Mui-selected:hover { ...

Leveraging MongoDB imported documents within DerbyJS

I am facing a challenge with my MongoDB collection which was not saved through my Derby app. My goal is to query that data and pull it into my Derby app. After figuring out the solution, I have written the following code snippet: get '/:year', ...

Three.js interpolation surface solution

Greetings everyone, I have a question regarding surfaces in Three.js. I have multiple Vec3 points and I want to create a surface that interpolates through them. While researching, I came across bezier curves (source: three.js bezier - but only as lines) a ...

Sass compilation with source mapping

Is there a more efficient method to compile my sass files with sourcemap enabled other than using the command below? sass --compass --sourcemap --style compact --watch sass:css In the case of utilizing compass, 'compass watch' would be the pref ...

Avoid showing duplicate values in the optgroup selection

Show the database value in the optgroup option. If the value of the parsing controller is equal to the option's value, do not display it within the HTML tag. Value of the parsing controller: {{$getData->status}} This is how my view blade looks: ...