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

What is causing the components to not re-render after a state change in React?

I am attempting to retrieve data from the Coin Market Cap API and showcase the details in simple cards. I have experimented with various methods and included comments to document my trials. Any assistance would be greatly appreciated. This is the Parent: ...

Eliminate the use of backslashes in JSON responses when using the WordPress REST API

As I work on extending the Wordpress Rest API, I encounter backslashes even after adding json flags to eliminate them. Below is what I am attempting: stripslashes(json_encode(['success'=> true], JSON_FORCE_OBJECT | JSON_HEX_APOS)); The outpu ...

Video player on website experiencing issues with playing VAST ads

Hey there! Check out this awesome site for Music Videos: (Music Videos(Player)) I've been testing different options, but if you have a better suggestion, please let me know. Any help would be really appreciated. If I can't figure it out on my o ...

Having trouble getting my HTML file and CSS styles to render properly in Chrome

Currently, I am in the process of developing a website and facing challenges with displaying CSS properties accurately. Despite seeking input from friends and users, my HTML file is not rendering as expected within various browsers such as Chrome, Edge, an ...

What is the best way to halt a JavaScript function originating from embedded iframe content?

When I embed another website using iframe, there is a javascript function on their page that I do not want to run on my own page. Here it is: if (top.location != location) { top.location.href = document.location.href; } I attempted a solution but it ende ...

Creating a dictionary or JSON object in Python from a string containing duplicate keys

Need help with parsing a JSON string stored in a variable that contains duplicate keys? Here's an example of the string: my_string_variable = """{ "a":1, "b":{ ...

Error: Trying to set a value to an undefined object in the bind() method

I am currently working on implementing a listener for my video player in order to update the input range on some custom controls. However, I have encountered an issue with an error message that states Uncaught ReferenceError: Invalid left-hand side in as ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

Update a DIV when ajax call is successful

I have a webpage with a specific heading: <div class="something"><? some php code ?></div> On this page, there is also an ajax function that performs a certain task: <script> $(document).ready(function () { $(document).ajaxSta ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

Using ui-grid to show cells as drop-down menus

I have a ui-grid example where one of the columns represents gender ('Gender': male, female...). The json data binding to the grid only contains code types like (1, 2, 3...). However, I want to display the gender name such as 'male' if ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

Changing the 'checked' attribute does not have any impact on how it appears in the browser

I am working on a button group where each button should light up when it is selected. The functionality is not fully working as expected; only one button should be active at a time. https://i.sstatic.net/oB9XG.png let stanceBar = ["long", "short", "out", ...

Having trouble loading JSON in Python line by line?

Presented here is the format of my JSON file: [{ "name": "", "official_name_en": "Channel Islands", "official_name_fr": "Îles Anglo-Normandes", }, and so forth...... Upon attempting to load the aforementioned JSON file, I encountered this error: json.d ...

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...