Caught in the midst of a JSON update conundrum

I need some help with my JavaScript/JSON coding. I have a script that loads JSON data and displays it on an HTML page. Now, I want to know how I can update this data. Specifically, I want the script to update the location of the person when a button is clicked.

Plaats = place postcode = zipcode

<!DOCTYPE html>
<html lang="en">
<body>
<p id="demo"></p>
<script>
var text = '{ "gebruikers" : [' +
'{"naam":"Johan de vries", "Plaats":"Otterlokade 56", "postcode":"6743FG", "Plaats":"Dinxperloo", "telefoon":"0495-1234567"},' +
'{"naam":"Jan de hoop", "Plaats":"Maaswijk 23", "postcode":"1234AK", "Plaats":"Hindelopen", "telefoon":"0345-1245677"},' +
'{"naam":"Marlies de hoop", "Plaats":"Maaswijk 23", "postcode":"1234AK", "Plaats":"Hindelopen", "telefoon":"0345-1245677"} ]}';
// Load JSON
obj = JSON.parse(text);


var longtext = "";
for (i = 0; i < obj.gebruikers.length; i++) {
// add json to longtext
    longtext += "<ul><li>" + obj.gebruikers[i].naam + "</li><li> " + obj.gebruikers[i].Plaats + "</li>" + obj.gebruikers[i].postcode + "</li><li>" + obj.gebruikers[i].Plaats + "</li><li>" + obj.gebruikers[i].telefoon + "</li></ul>" ;
}

function myChange() {
// load names
var selector = document.getElementById('namen');
var value = selector[selector.selectedIndex].value;
// Load places
var plaatsen = document.getElementById('plaatsen');
var plaatsen = plaatsen[plaatsen.selectedIndex].value;


  for (var i=0; i<text.length; i++) {
    if (longtext[i].naam == value) {
      longtext[i].Plaats = plaatsen;
      break;
    }
  }
}

document.getElementById("demo").innerHTML = longtext;


</script>

<select name="plaatsen">
  <option value="Amersfoort">Amersfoort</option>
  <option value="Utrecht">Utrecht</option>
  <option value="Amsterdam">Amsterdam</option>
</select>
<select name="namen">
  <option value="Johan de vries">Johan de vries</option>
  <option value="Jan de hoop">Jan de hoop</option>
  <option value="Marlies de hoop">Marlies de hoop</option>
</select>

<input type="submit" onclick="myChange()">

</body>
</html>

Answer №1

To update the object and show the list again.

var data = '{ "users" : [' +
  '{"name":"John Smith", "Address":"123 Main St", "zipcode":"90210", "City":"Beverly Hills", "phone":"555-1234567"},' +
  '{"name":"Jane Doe", "Address":"456 Elm St", "zipcode":"54321", "City":"Springfield", "phone":"444-9876543"},' +
  '{"name":"Alice Johnson", "Address":"789 Oak St", "zipcode":"67890", "City":"Oakland", "phone":"333-5678912"} ]}';
var object = JSON.parse(data);

var displayBox = document.getElementById("displayBox");
var cities = document.getElementById("cities");
var names = document.getElementById("names");

showInfo();

function showInfo() {
  var output = "";
  for (i = 0; i < object.users.length; i++) {
    output += "<ul><li>" + object.users[i].name + "</li>" +
      "<li> " + object.users[i].Address + "</li>" +
      "<li>" + object.users[i].zipcode + "</li>" +
      "<li>" + object.users[i].phone + "</li></ul>";
  }
  displayBox.innerHTML = output;
}

function makeChanges() {
  let city = cities.value;
  let person = names.value;

  var toUpdate = object.users.find(o => o.name === person);
  toUpdate.City = city;
  
  showInfo();
}
<body>
  <p id="displayBox"></p>

  <select name="cities" id="cities">
    <option value="New York City">New York City</option>
    <option value="Los Angeles">Los Angeles</option>
    <option value="Chicago">Chicago</option>
  </select>
  
  <select name="names" id="names">
    <option value="John Smith">John Smith</option>
    <option value="Jane Doe">Jane Doe</option>
    <option value="Alice Johnson">Alice Johnson</option>
  </select>

  <input type="submit" onclick="makeChanges()">

</body>

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

Ajax sending numerous requests to the API

Recently, I began my journey of learning Javascript and decided to interact with my Django API through Ajax requests. To achieve this, I created a search bar that triggers the API call after a one-second delay following a keyup action. input.addEventListe ...

Disregarding issues encountered while parsing a particular property with an unresolved type during deserialization

When serializing a type that includes an object property, such as the example below: class MyData { ... various properties ... object UserProp; } By using TypeNameHandling.Auto, the deserialization process generally works well, but only if the de ...

Using XSL variables in JavaScript code

I've noticed that there have been similar questions asked, but none of the solutions seem to help in my case. So, I have this variable named 'var': <xsl:variable name="var"> val </xsl:variable> Now, I want to use it like thi ...

Challenges faced with Vuetify's vertical and non-linear stepper components

I've been struggling to grasp the concept of Vuetify's stepper feature. Despite my efforts, I haven't been successful in combining different steppers from their page that each have elements I need but lack others. One example is this one on ...

Permit the use of backslashes in the API JSON

I recently developed a straightforward Add API using C# .NET Core v5. Here is the format: { groupname: string, groupdescription: string, filedirectory: string } When it comes to the filedirectory, I need to input the value like E:\Fil ...

Modifying the text within the label of a multibarchart in nvd3.js

After analyzing the multibarchart in nvd3.js, I have discovered that it requires a specific JSON format as input. [ { "key": "abcd", "values": [ { "x": 1221578789000, "y": 40 }, { "x": 1222578789000, ...

The URL for the Javascript chunk includes colons at https://example.com/js/chunk-vendors.b3792e11.js:18:16400

I recently completed a Vue application and used npm run build to generate the files. Upon uploading the dist folder to my Apache server, I encountered an issue where Apache was unable to locate the file when trying to access a specific part of the app (:18 ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

Different ways to modify the color of a chart using am4chart

I am using am4chart to create a line chart on my website. The background of the website is black, so I need to make the chart white. I have tried changing the chart fill when creating the chart, but it didn't work at all. However, changing the chart ...

Guide to Displaying JSON Objects and Arrays in an Android ListView

I am new to developing Android apps and I'm struggling with how to parse JSON objects and arrays into a ListView in Android. Below is the JSON output: UPDATED WITH CORRECTED JSON {status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myn ...

How can you extract a specific object from a JSON string?

Currently, I am working on a script using JQuery within an ASP.NET page. Here is an example of a JSON string that I am dealing with: <input id="hfImages" type="hidden" value="[ {"ProductID": "000001", "Small": "http://myimages.com/images/I/75.jpg", " ...

Is it possible to format JSON data so that it can be easily read by a Google spider?

Is it possible for a Google spider to understand and interpret JSON data? Imagine having a JSON feed that holds information for an e-commerce website. This JSON data is used to populate a page that can be read by users in their browser. (Essentially, the ...

Over-extended Affix in Bootstrap 3.1.0

I'm currently using Bootstrap 3.1.0. The issue I've encountered is that when the "affix" becomes too long for the viewport, it ends up getting cut off and doesn't display the bottom items. Is there a way to make Bootstrap's affix featu ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

Anticipated the start of an object but instead found a number

After receiving this JSON response from a REST server: { "externalOrderId":"5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea", "shortId":null, "createdAt":1442255497402, "updatedAt":1442255497402, "cart":{ "id":"gy4ectxb3db84epljzhisqrf" } ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

The structure of NodeJS Express API calls revolves around handling asynchronous events

Currently, I am working on a hobby project using NodeJS and Express, but I am finding it challenging to manage asynchronous calls. There is a bug that I would like the community's help in resolving. I have set up an Express layout where I send post r ...

Activation of states in response to item clicks

Recently, I started using the US-Map plugin created by newsignature (). I have put together a chart that highlights various state laws for comparison on a per-state basis. Currently, the setup allows me to compare 3 states at a time. Users can easily clos ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...