Developing two HTML tables utilizing JavaScript

I've encountered an issue while trying to generate 2 dynamic html tables using JavaScript with data from HTML inputs. Successfully creating the first table, I faced difficulties in creating another table utilizing different input fields on the same page.

Upon attempting to modify the addRow() functions in both the HTML and JS files by assigning distinct names, both tables ended up failing to render properly.

If anyone could offer assistance, it would be greatly appreciated. Below is the experimental code that I've been working with:

<!DOCTYPE html>

<body onload="load()">
<div id="myform">

<table>
    <tr>
        <td>Name:</td>
        <td><input type="text" id="name"></td>
      </tr>
    <tr>
        <td>Age:</td>
        <td><input type="number" id="age">
            <input type="button" id="add" value="Add" onclick="addRow()"></td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>
<br>
<table>
    <tr>
        <td>Height:</td>
        <td><input type="text" id="height"></td>
    </tr>
    <tr>
        <td>Width:</td>
        <td><input type="text" id="width">
            <input type="button" id="addDim" value="Add" onclick="addRow()"></td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

</div>
<div id="mydata">

<table id="myTableData" border="1" cellpadding="2">
    <tr>
        <td>&nbsp;</td>
        <td><b>Name</b></td>
        <td><b>Age</b></td>
    </tr>
</table>
&nbsp;

<table id="myTableData2" border="1" cellpadding="2">
    <tr>
        <td>&nbsp;</td>
        <td><b>Height</b></td>
        <td><b>Width</b></td>
    </tr>
</table>


</body>
</html>



function addRow() {

    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    var table = document.getElementById("myTableData");

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="deleteRow(this)">';
    row.insertCell(1).innerHTML= myName.value;
    row.insertCell(2).innerHTML= age.value;

    var width = document.getElementById("width");
    var height = document.getElementById("height");
    var table2 = document.getElementById("myTableData2");

    var rowCount2 = table2.rows.length;
    var row2 = table2.insertRow(rowCount2);

    row.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
    row.insertCell(1).innerHTML = width.value;
    row.insertCell(2).innerHTML = height.value;

}

function deleteRow(obj) {
    var index = obj.parentNode.parentNode.rowIndex;
    var table = document.getElementById("myTableData");
    table.deleteRow(index);
}

function load() {
    console.log("Page load finished");
}

Answer №1

It appears that the row2 variable you defined in the bottom section is not being utilized.

The correct implementation should look like this:

var rowCount2 = table2.rows.length;
var row2 = table2.insertRow(rowCount2);

row2.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
row2.insertCell(1).innerHTML = width.value;
row2.insertCell(2).innerHTML = height.value;

Answer №2

Here is my approach to solving it. The function I created can be used for any number of tables by passing parameters into the function.

Check out the code here!

function populateTable(tableName) {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var age = document.getElementById('age').value;

var information = [firstName, lastName, age];

var table = document.getElementById(tableName);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cellCount = table.rows[0].cells.length; 

for(var i=0; i < cellCount; i++) {
    row.insertCell(i).innerHTML = information[i];
    } 
}

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

Unable to load page redirection

I am experiencing an issue with this page not redirecting to the appropriate mobile or desktop page when accessed. Below is the code snippet in question: <html> <head> <title>Loading...</title> </head> < ...

What is causing MongoDB to delete documents based on TTL even when the partial filter does not align with the specified option?

I noticed that my partial filter is deleting documents even when the user does not meet the specified requirement. Could it be possible that I am using the partial filter incorrectly? Thank you for your assistance. const postSchema = new mongoose.Schema ...

Discovering the element's class within an each loop

I am currently working on a dynamic menu system that changes the style of the active page item in the menu. My approach involves utilizing separate body classes for each page and then iterating through the li elements in the menu to find a match with the b ...

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

Hyperlinks springing to life on mouseover

After spending countless hours tweaking my CSS code, I've hit a roadblock and need some assistance. My issue lies with the links on hover that seem to be jumping unexpectedly. The goal was to create a mobile-responsive hamburger menu that transforms i ...

Content refuses to show up on my social networking website project when Ajax is employed

I've been working on a Social Media website for a major project, and I recently implemented Ajax to load posts. However, I'm facing an issue where the content is not displaying on the index page after implementation. My goal is to load 10 posts a ...

Incorporate a captivating background image onto the homepage of your Quarto website

How can I add a background image to fill the entire page on the home page only in a Quarto website? I currently have a solution that adds the background image, but it applies it across the entire website. In this case, I want to exclude the report page fr ...

Is there a way to efficiently receive messages from the backend in an asynchronous manner

When a user enters a username, I need to verify its availability by sending it to the backend. I currently have code in place for this process, but I am unsure about how to receive the message regarding whether the username is available or unavailable. ...

Dynamic drop-down navigation with rearranging menu

I am attempting to design a drop-down navigation bar with 2 rows. Initially, only 1 row is visible. Upon clicking the visible row, both rows should appear. Subsequently, when one of the 2 rows is clicked, only that specific row should be displayed. Below a ...

Creating form inputs dynamically in HTML and then sending them to a PHP script programmatically

On my webpage, users can click a button to add new form inputs as needed. However, I'm running into an issue trying to access these new inputs in the PHP file where I submit the data. Here is the code snippet for the button within the form on the pag ...

distinguishing the container component from the presentational component within react native

I just started developing apps using React Native and implemented a basic login function with the view and login logic on the same page named HomeScreen.js. However, after reading some articles online, I learned that it's recommended to separate the l ...

Concentrate on Input in the Middle of the Text

Is it feasible to target a specific character within an input using JavaScript/jQuery for focus? Consider this input field: Would it be achievable to focus on the element and position the cursor after the first sentence, as an illustration? ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

Incredibly peculiar actions exhibited by a coffeescript/javascript array of functions

Something strange is happening with my code in Chrome, creating a mysterious quantum duel state where functions turn into undefined when pushed to an array... eerie! I am constructing an array of functions using the code below to chain them together for c ...

Unable to interpret JSON data in D3visualization

While attempting to read a JSON file using the D3 library, I encountered an issue where I received an alert indicating null values. Here is the code snippet I am using: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" ...

Difficulty with CasperJS multi-select functionality

I am currently attempting to utilize CasperJS for choosing both options in a multiple select within an HTML form: <select id="bldgs" name="bldgs" multiple="multiple" size="6" autocomplete="off"> <option value="249759290">Southeast Financia ...

Using an HttpInterceptor in Angular 1.5 for managing timeouts

Hello everyone, I have been attempting to implement a global httpInterceptor that will display a custom popup message when a client timeout occurs, rather than a server timeout. I came across a helpful article on this topic: Angular $http : setting a prom ...

Tips on sending information from Express to my HBS template

var Ticket = require('./models/ticket.js'); module.exports = function (app) { app.get('/',function (req, res) { Ticket.find({},function (err, tickets) { if(err) { res.sen ...