Encountering issues with JavaScript when attempting to add a new item to an HTML table as initially planned

I’m having an issue where whenever I add a new item to my table, it ends up at the top and replaces the original header. I would prefer if the new item gets added as the last row.

Here is a screenshot of the problem:

  
            var rIndex,
                table = document.getElementById("table");
            
            // checking for empty input
            function checkEmptyInput()
            {
                var isEmpty = false,
                    Uname = document.getElementById("Uname").value,
                    Cname = document.getElementById("Cname").value,
                    Tname = document.getElementById("Tname").value,
                Kname = document.getElementById("Kname").value,
                    Mname = document.getElementById("Mname").value,
                    Oname = document.getElementById("Oname").value;
            
                if(Uname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }
                else if(Cname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }
                else if(Tname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }else if(Kname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }
                else if(Mname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }else if(Oname === ""){
                    alert("This field cannot be empty");
                    isEmpty = true;
                }
                return isEmpty;
            }
            
            // adding a new row to the table
            function addHtmlTableRow()
            {
                if(!checkEmptyInput()){
                    var newRow = table.insertRow(table.length),
                        cell1 = newRow.insertCell(0),
                        cell2 = newRow.insertCell(1),
                        cell3 = newRow.insertCell(2),
                        cell4 = newRow.insertCell(3),
                        cell5 = newRow.insertCell(4),
                        cell6 = newRow.insertCell(5),
                        Uname = document.getElementById("Uname").value,
                        Cname = document.getElementById("Cname").value,
                        Tname = document.getElementById("Tname").value,
                        Kname = document.getElementById("Kname").value,
                        Mname = document.getElementById("Mname").value,
                        Oname = document.getElementById("Oname").value;
                    
                    cell1.innerHTML = Uname;
                    cell2.innerHTML = Cname;
                    cell3.innerHTML = Tname;
                    cell4.innerHTML = Kname;
                    cell5.innerHTML = Mname;
                    cell6.innerHTML = Oname;
                    // call the function to set the event to the new row
                    selectedRowToInput();
                }
            }
            
            // displaying data from selected row into input text fields
            function selectedRowToInput()
            {
                for(var i = 1; i < table.rows.length; i++)
                {
                    table.rows[i].onclick = function()
                    {
                        // get the selected row index
                        rIndex = this.rowIndex;
                        document.getElementById("Uname").value = this.cells[0].innerHTML;
                        document.getElementById("Cname").value = this.cells[1].innerHTML;
                        document.getElementById("Tname").value = this.cells[2].innerHTML;
                        document.getElementById("Kname").value = this.cells[3].innerHTML;
                        document.getElementById("Mname").value = this.cells[4].innerHTML;
                        document.getElementById("Oname").value = this.cells[5].innerHTML;
                    };
                }
            }
            selectedRowToInput();
            
            function editHtmlTableSelectedRow()
            {
                var Uname = document.getElementById("Uname").value,
                    Cname = document.getElementById("Cname").value,
                    Tname = document.getElementById("Tname").value,
                    Kname = document.getElementById("Kname").value,
                    Mname = document.getElementById("Mname").value,
                    Oname = document.getElementById("Oname").value;
                    
               if(!checkEmptyInput()){
                    table.rows[rIndex].cells[0].innerHTML = Uname;
                    table.rows[rIndex].cells[1].innerHTML = Cname;
                    table.rows[rIndex].cells[2].innerHTML = Tname;
                    table.rows[rIndex].cells[3].innerHTML = Kname;
                    table.rows[rIndex].cells[4].innerHTML = Mname;
                    table.rows[rIndex].cells[5].innerHTML = Oname;
              }
            }
            
            function removeSelectedRow()
            {
                table.deleteRow(rIndex);
                document.getElementById("Uname").value ="";
                document.getElementById("Cname").value ="";
                document.getElementById("Tname").value ="";
                document.getElementById("Kname").value ="";
                document.getElementById("Mname").value ="";
                document.getElementById("Oname").value ="";
            }
.container{overflow: hidden}
            .tab{float: left;}
            .tab-2{margin-left: 50px}
            .tab-2 input{display: block;margin-bottom: 10px}
            tr{transition:all .25s ease-in-out}
            tr:hover{background-color:#EEE;cursor: pointer}
            
<!DOCTYPE html>
<html>
    <head>
        <title>Add Edit Remove HTML Table Row</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <style>
            
            .container{overflow: hidden}
            .tab{float: left;}
            .tab-2{margin-left: 50px}
            .tab-2 input{display: block;margin-bottom: 10px}
            tr{transition:all .25s ease-in-out}
            tr:hover{background-color:#EEE;cursor: pointer}
            
            </style>
        
    </head>
    <body>
        
        <div class="container">
            <div class="tab tab-1">
                <table id="table" border="1" >
                    <tr class="header">
                <th class="style2">Unit Num.</th>
                <th class="style3">Computer</th>
                <th class="style3">Tower</th>
                <th class="style9">Keyboard</th>
                <th class="style3">Mouse</th>
                <th class="style4">Overall State</th>
            </tr>
            <tr>
                 <td class="style5">1</td>
                 <td class="style5">1</td>
                 <td class="style5">1</td>
                 <td class="style7">1</td>
                 <td class="style5">1</td>
                 <td class="style6">Very Good</td>
            </tr>
                    <tr>
                        <td>A1</td>
                        <td>B1</td>
                        <td>10</td>
                        <td>A1</td>
                        <td>B1</td>
                        <td>10</td>
                    </tr>
                    
                </table>
            </div>
            <div class="tab tab-2">
       Unit Number :<input type="number" name="Uname" id="Uname">
       Computer ID :<input type="number" name="Cname" id="Cname">
       Tower ID :<input type="number" name="Tname" id="Tname">
  Keyboard ID :<input type="number" name="Kname" id="Kname">
     Mouse ID :<input type="number" name="Mname" id="Mname">
      Overall State :<input type="number" name="Oname" id="Oname">
                
    <button onclick="addHtmlTableRow();">Add</button>
    <button onclick="editHtmlTableSelectedRow();">Edit</button>
    <button onclick="removeSelectedRow();">Remove</button>
            </div>
        </div>
   </body>
</html>

Answer №1

        if(!validateInput()){
            let newTableRow = table.insertRow(table.rows.length),
                cell1 = newTableRow.insertCell(0),
                cell2 = newTableRow.insertCell(1),

Correct the code snippet by updating table.length to table.rows.length. The variable table, which is an instance of HTMLTableElement, does not have a length property.

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

Dynamic background image that fills the entire webpage, adjusts to different screen sizes, and changes randomly

Currently, I am working on designing a web page with a dynamic background image that adjusts responsively in the browser without distortion. The challenge is to randomly select an image from an array using jQuery. Unfortunately, my knowledge of jQuery is ...

JS form submission problem

Seeking advice on developing a functional contact form using HTML, CSS, and JavaScript. All conditions currently validate properly, but encountering an issue with error messages persisting after re-entering the required fields. Additionally, looking to red ...

What is the method to define YAML array indices in JavaScript?

I apologize for my previous post. I have successfully integrated a RapidAPI for Covid-19 updates, which is now outputting the results as an array JSON in the console. You can view the YAML Array Output here. I am now facing a challenge in listing specifi ...

What is the best way to change the class of the inline table of contents element using JavaScript?

INQUIRY Hello, I am currently working on building a straightforward navigation site and I have a question regarding how to modify or add a class to one of the li elements within the inline table of contents (toc) on the right side. I want to style it usin ...

Steps for incorporating a side panel next to a component with carbon components

I'm working on a Sveltekit app and I want to create a homepage that displays a table using carbon components. The twist is, I also need to add a filter panel next to the table for data filtering. Essentially, I am aiming to achieve something similar t ...

JavaScript's ability to pinpoint individual hits stands out as a distinguishing feature

Is there a creative approach to identifying a distinct user using JavaScript, such as generating a hash to transmit to the server-side? EDIT: The challenge is that I am unable to access the browser directly (e.g. set cookies). Additionally, relying on IPs ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Having trouble loading a JavaScript file in Nuxt? Experiencing some unexpected behavior?

I have a template with HTML/CSS/JS files that I want to make dynamic using Nuxt.js. I started by copying the index.html to the Nuxt project and transferring all the necessary data to nuxt.config.js, including CSS and JS files. The page renders without erro ...

Calculating the area of neighboring triangles using Three.js

Looking to determine the area of triangles surrounding a specific vertex within a mesh using Three.js. I am aware that in three.js, faces represent the connections between vertices in a mesh. However, I have yet to find an effective method for identifying ...

"Unstable Page Refreshes: The issue of flickering in Laravel 5.3 with Vue 2

Each time I refresh my page, instead of seeing my Vue content, it appears briefly and then disappears (flickers). This is my app.js file: require('./bootstrap'); var Vue = require('vue'); new Vue({ el: '#root', data: { ...

Retrieving data from the state in a React Component

As I am still learning about reactjs, I have come across the difference between React.createclass and React.component. In React.createclass, you can easily access an input value or any state value using code like this: change: function(e) { this.set ...

Forward to a different page after sending an ajax request

Hello, I am currently utilizing an ajax script that redirects to a PHP page for validation. Once all validation checks are successfully passed, I am trying to redirect to another page but encountering difficulties in implementing this functionality. Below ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

Creating a new array from a Flood Fill operation in JavaScript

I am seeking guidance on modifying this algorithm to generate a new array of updated elements instead of altering the global map array. This is the JavaScript implementation of the Flood Fill algorithm. Starting Array: var map = [ [0, 0, 0, 1, 1], ...

What is the best way to ensure that a Material UI transition component fully occupies the space of its parent component?

I've been experimenting with a Material UI transition component in an attempt to make it completely fill its parent container. So far, I've achieved some success by setting the width and height to 100% and applying a Y-axis translation for the co ...

Creating a Sleek Horizontal Scroll Functionality for Multiple Rows with Bootstrap 5

The container allows scrolling for only half of its content. Afterwards, scrolling affects the navigation panel as well. CSS: .horizontal-scrollable { overflow-x: auto; white-space: nowrap; } HTML: <div class="container hori ...

What is the maximum size allowed for a Text field in MySQL?

I am currently working on a project that involves users posting text using TinyText. I found out that TinyText only allows 255 characters to be entered after visiting . However, if a user enters an ampersand (&), it needs to be converted to &amp and so ...

What is the best method for aligning a div in Internet Explorer 9 with the help of JavaScript?

The code in this Javascript function is not responding as expected in IE9, although it functions correctly in Chrome. function adjustDivPosition(divID,leftPos,topPos) { document.getElementById(divID).style.left = leftPos; document.getElementById( ...

rearrange the div elements by shifting each one into the one preceding it

Do you consider this a child and parent div relationship? <div class="container"> <p>content</p> </div> <div class="footer"><p>content</p></div> <div class="container"> <p>content</p> < ...