As it showcases new information, it also retrieves and displays old data stored locally

function addNewRow() {
    debugger;
    var personList = [];
    if (localStorage.person1 != null && localStorage.person1 !=undefined) {
        var personList = JSON.parse(localStorage.person1);
    }

    var name = document.getElementById('name').value;
    var city = document.getElementById('city').value;
    personList.push({ 
        pname: name,
        pcity: city
    });

    localStorage.setItem('person1', JSON.stringify(personList));
    displayRows();
}

function displayRows() {
    debugger;
    var per_list = JSON.parse(localStorage.getItem('person1'));
    for (i = 0; i < per_list.length; i++ ) {
        var table = document.getElementById('ptable');
        var row = table.insertRow(0);
        var col1 = row.insertCell(0);
        var col2 = row.insertCell(1);
        col1.innerHTML = per_list[i].pname;
        col2.innerHTML = per_list[i].pcity;
    }
}

I have two fields name and city; Now, clicking on "add row" prints ok for the first value, but afterwards it is printing both the old and new values. I want only the new entry to be displayed below the old input. Thanks in advance.

Answer №1

To ensure all elements in the .bind function are displayed, it is necessary to refresh the table content.

function bind() {
  debugger;
  var personList = JSON.parse(localStorage.getItem('person1'));
  // Clearing the table
  var table = document.getElementById('ptable');
  for (var i = 0, rows = table.rows.length; i < rows; i++) {
    table.deleteRow(0)
  }
  // Filling the table with updated information
  for (i = 0; i < personList.length; i++) {
    var row = table.insertRow(0);
    var col1 = row.insertCell(0);
    var col2 = row.insertCell(1);
    col1.innerHTML = personList[i].pname;
    col2.innerHTML = personList[i].pcity;
  }
}

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 process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Using React: What is the best method for handling asynchronous requests to fetch a FirebaseToken and subsequently utilizing it in an API request?

My React app is interacting with an API through a Client component. Components can access the Client like this (example in the componentDidMount function of the Home page, where I retrieve a list of the user's items): componentDidMount() { let u ...

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...

What is the best way to transform a rawString into a JSON Array?

I'm having trouble converting jsonString.rawString() into a JSON object, as it keeps returning nil. let jsonData = newsfeedData.rawString()?.data(using: .utf8) let object = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainer ...

Discovering trustworthy dependency packages through NPM: A Guide

For instance, when adding a new dependency package using shell: npm install typescript I have no knowledge of the provider behind that package. In contrast, in Maven (a Java package manager), you add a new dependency package by modifying the xml configur ...

Leverage the inherent capabilities of jQuery to seamlessly transmit form data via ajax using the pre-existing

Snippet of Code: <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ header('Content-Type: application/json'); echo json_encode($_POST); exit(0); } ?> <html> <head> <titl ...

Adjusting the positioning of the label in a d3 line graph

Here is the data file named: myStData.csv xindex,mylabel 40,23 41,13 42,12 43,21 44,40 45,50 In this code snippet, the label is currently shown at the "start" position (text-anchor set to start). The label is placed according to the start value in the cs ...

How should an iterable be sorted in React?

Let's break down the scenario using pseudo code: {this.props.myIterable.map((iterable) => { return ( <div>iterable.somevalue</div> ) }).sort((a,b) => {return b - a}) To clarify, I am iterating over certain props and displaying ...

C++ - Analyzing input file data and generating statistical insights

After initially posting a question about this topic, I have made significant progress in working on the source code. However, I am currently facing challenges due to various inconsistencies and issues within my source code. Despite that, please disregard ...

How to Make a Zigzag Formation in three.js?

I have been working on developing a 3D tool and was in need of a zigzag structure. I managed to create it by iterating a function that produces 'V' multiple times, but now I am looking for a way to achieve the same effect using a single geometry ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

Double submission issue plagues Vue component

My data model involves a Site with coordinates that can be linked to an Observation. When a user submits both a Site and Observations, they are stored in IndexedDB using localForage. The Outbox component handles posting these to the server when the user is ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

What is the functionality of the "async:false" setting in a jQuery AJAX request?

I understand the purpose and usage of {async:false} in jQuery AJAX requests. However, I am curious to know how this operates synchronously. What is the mechanism behind it? ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Converting JSON information into a mailto hyperlink

Can anyone help me figure out how to encode a mailto link properly with JSON data in the query parameters, ensuring that it works even if the JSON data contains spaces? Let's consider this basic example: var data = { "Test": "Property with spaces" ...

Guidelines for Sending PHP (index.php file) Variable Value to External JavaScript .js File

In the current code snippet, index.php file contains JavaScript array values that I would like to pass to an external JavaScript file. <?PHP $qry2 = mysql_query("SELECT table_no FROM table_info"); while($res2 = mysql_fetch_array($qry2)) { st ...

What is the best way to halt Keyframe Animation once users have logged in?

To enhance user engagement, I incorporated keyframe animation into my login icon on the website. The main objective is to capture the attention of visitors who are not registered users. However, once a user logs in, I intend for the keyframe animation to c ...

Setting the width of a parent div tag in CSS based on its children tags

My goal is to have a parent div tag with several children div tags placed horizontally. Since the number of children tags is not known in advance, I cannot set the width of the parent div tag using CSS alone, so I am using JavaScript for this purpose. var ...

Encountering a CORS policy error in Three.js when attempting to run locally

I'm just starting out on this website and I'm eager to dive into learning javascript. My initial attempt at following this example from resulted in an error without any animation or background showing up. Instead, all I see is a photo displayin ...