What is the best way to remove existing values and update with new values from a JSON using JavaScript?

The following is an excerpt of html code:

 <div id="prt">
         <select name="selectPrt" class="span12" onchange="sta_callPRT();">
          <option value="noPrt">Choose one vehicle.</option>
          <option value="prt1">PRT 1</option>
          <option value="prt2">PRT 2</option>
          <option value="prt3">PRT 3</option>
          <option value="prt4">PRT 4</option>
          <option value="prt5">PRT 5</option>
        </select>
        <div class="row-fluid">
         <div class="span6">
           <div class="section">
            <div class="sectionTitle">
              <h3>Vehicle Info</h3>
            </div>
          </div>
<div id="state"><strong>State:</strong> </div>
          <div id="freeSeats"><strong>freeSeats:</strong></div>
          <div id="battery"><strong>battery:</strong></div>
          <div id="totalDistance"><strong>totalDistance:</strong></div>
          <div id="location"><strong>Location:</strong></div>
          <div id="estimatedTime"><strong>estimatedTime"</strong></div>
          <div id="estimatedDistance"><strong>estimatedDistance:</strong></div>
          <div id="speed"><strong>speed:</strong></div>

In addition, there is the following Javascript:

function sta_callPRT(){

    $.getJSON('PRTInfoGenerator.php', function(json){

        $.each(json, function(key, value) {

       if(key=="state") {
          //$('#state').empty();
          //document.getElementById("parameters").appendChild(divTag);
          $('#state').append(value);
                      }
       if(key=="freeSeats") {
          $('#freeSeats').append(value);
        }
       if(key=="estimatedDistance"){
        $('#estimatedDistance').append(value);
       }
        if(key=="estimatedTime"){
        $('#estimatedTime').append(value);
       }
        if(key=="battery"){
        $('#battery').append(value);
       }
        if(key=="speed"){
        $('#speed').append(value);
       }
        if(key=="location"){
          $.each(json.location, function(par_key, par_value) {

        $('#location').append(par_key+': '+par_value+'  ');
      });
       }
       if(key=="totalDistance"){
        $('#totalDistance').append(value);
       }
    });

  });
  }

I am looking to display random vehicle values in the HTML. I have PHP code that generates these random values for vehicles. When a vehicle is selected, it displays certain values. However, when a new selection is made, the new values are simply added to the existing ones. How can I remove the previous values and replace them with the new values upon a new selection?

For example, here is the result after the first selection:

State: Running
freeSeats:0
battery:95
totalDistance:8541
Location:x: -5 y: 34
estimatedTime:15
estimetedDistance:809
Speed:18

And here is the result after the second selection:

State: RunningRunning
freeSeats:04
battery:9540
totalDistance:85411848
Location:x: -5 y: 34 x: 84 y: -70
estimatedTime:15269
estimetedDistance:809513
Speed:1818

Answer №1

One efficient way to empty the divs every time...

const clearDivs = () => {
     $('#state, #freeSeats, #battery').empty();

     $.getJSON('PRTInfoGenerator.php', function(json){
           ...

Answer №2

To reposition the prefix text outside the divs, use

freeseats: <div id="freeSeats"></div>
and replace $('#freeSeats').append(value); with $('#freeSeats').text(value). Appending will add to the existing content, whereas using text will overwrite the current value.

If you need to alter text within strong tags, consider using $('#freeSeats strong'). It is recommended to avoid strong tags and apply styling directly on the div elements instead.

Here is the modified code:

<div id="prt"> 
          <select name="selectPrt" class="span12" onchange="sta_callPRT();">
          <option value="noPrt">Choose one vehicle.</option>
          <option value="prt1">PRT 1</option>
          <option value="prt2">PRT 2</option>
          <option value="prt3">PRT 3</option>
          <option value="prt4">PRT 4</option>
          <option value="prt5">PRT 5</option>
        </select>
        <div class="row-fluid">
         <div class="span6">
           <div class="section">
            <div class="sectionTitle">
              <h3>Vehicle Info</h3>
            </div>
          </div>
          State:<div id="state"></div>
          freeSeats:<div id="freeSeats"></div>
          battery:<div id="battery"></div>
          totalDistance:<div id="totalDistance"></div>
          Location:<div id="location"></div>
          estimatedTime"<div id="estimatedTime"></div>
          estimatedDistance:<div id="estimatedDistance"></div>
          speed:<div id="speed"></div>

And here is the updated script:

function sta_callPRT(){

$.getJSON('PRTInfoGenerator.php', function(json){

    $.each(json, function(key, value) {

   if(key=="state") {
      $('#state').text(value);
                  }
if(key=="freeSeats") {
      $('#freeSeats').text(value);
}
       if(key=="estimatedDistance"){
    $('#estimatedDistance').text(value);
   }
if(key=="estimatedTime"){
    $('#estimatedTime').text(value);
}
      if(key=="battery"){
    $('#battery').text(value);
}
 if(key=="speed"){
    $('#speed').text(value);
}
     if(key=="location"){
      $.each(json.location, function(par_key, par_value) {

    $('#location').text(par_key+': '+par_value+'  ');
  });
}
if(key=="totalDistance"){
    $('#totalDistance').text(value);
}
});</answer2>
<exanswer2><div class="answer" i="15683879" l="3.0" c="1364464934" m="1364481250" a="YW50aG9ueWJlbGw=" ai="1536499">
<p>Move the prefix text to outside the divs like <code>freeseats: <div id="freeSeats"></div> and
use $('#freeSeats').text(value) instead of  $('#freeSeats').append(value);
appending will append whats already there but text will replace the value instead.

to change the text in the strong tags though you would want to use $('#freeSeats strong') but I recommend not using strong tags and use a style attribute on your div/divs instead.

here is your updated code then:

<div id="prt"> 
          <select name="selectPrt" class="span12" onchange="sta_callPRT();">
          <option value="noPrt">Choose one vehicle.</option>
          <option value="prt1">PRT 1</option>
          <option value="prt2">PRT 2</option>
          <option value="prt3">PRT 3</option>
          <option value="prt4">PRT 4</option>
          <option value="prt5">PRT 5</option>
        </select>
        <div class="row-fluid">
         <div class="span6">
           <div class="section">
            <div class="sectionTitle">
              <h3>Vehicle Info</h3>
            </div>
          </div>
          State:<div id="state"></div>
          freeSeats:<div id="freeSeats"></div>
          battery:<div id="battery"></div>
          totalDistance:<div id="totalDistance"></div>
          Location:<div id="location"></div>
          estimatedTime"<div id="estimatedTime"></div>
          estimatedDistance:<div id="estimatedDistance"></div>
          speed:<div id="speed"></div>

and the script:

function sta_callPRT(){

$.getJSON('PRTInfoGenerator.php', function(json){

    $.each(json, function(key, value) {

   if(key=="state") {
      $('#state').text(value);
                  }
   if(key=="freeSeats") {
      $('#freeSeats').text(value);
    }
   if(key=="estimatedDistance"){
    $('#estimatedDistance').text(value);
   }
    if(key=="estimatedTime"){
    $('#estimatedTime').text(value);
   }
    if(key=="battery"){
    $('#battery').text(value);
   }
    if(key=="speed"){
    $('#speed').text(value);
   }
    if(key=="location"){
      $.each(json.location, function(par_key, par_value) {

    $('#location').text(par_key+': '+par_value+'  ');
  });
   }
   if(key=="totalDistance"){
    $('#totalDistance').text(value);
   }
});

`

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

Modifying the information displayed in a navigation panel or division using JavaScript

I am working on a navigation system that looks like this: <nav class="subnav"> <ul> <li><a href="a.html">This link leads to content A.</a></li> <li><a href="a.html">This link goes to content B.</a> ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

Restricting Jackson Serialization/Deserialization Depth for every class

I experimented with using the CustomJSONSerializer as suggested in this discussion on Stack Overflow. However, I encountered the following error: com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class (through ...

Flutter is failing to display the data from the server API

I am currently learning Flutter and attempting to display server responses on my screen. I have successfully fetched data from server APIs, but I am facing an issue in displaying the data. Since I lack experience with working with API data and making requ ...

Error: The JSON data is invalid and contains an unexpected token B at the beginning. This issue is likely coming from

Recently, I encountered an issue while working with a JSON rest API and its response structure. Take a look at the sample response data below: // response [ { id: 1, userId: 1, start: "2018-01-01 10:15", finish: "2018-01-01 ...

What are the best ways to create image animations on top of other images using CSS or JavaScript?

Imagine if the first image is in black and white, while the second one is colored. How can we make the black and white image change to color after a timeout period, with an animation similar to loading progress bars? Is this achievable using CSS or JavaScr ...

I am attempting to separate this "for" loop in order to generate five distinct DIV elements

Hello there! I am a beginner and I am attempting to create 5 different players by using some code that I found. Here is the code I have been working with: https://codepen.io/katzkode/pen/ZbxYYG My goal is to divide the loop below into 5 separate divs for ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Handling Nested JSON arrays within an MVC Controller

Seems like a bit of a silly question, but I'm struggling to figure it out. Within a C# MVC Controller action, I am trying to model a Json Array for testing purposes. However, instead of getting a valid Json, I am encountering compilation errors with ...

working with JSON variables in Swift

Hello, I am new to Swift and programming. I am trying to work with JSON data but having trouble understanding it. Here is a snippet of the JSON I am working with: { "nextUpdate":300, "subscriptions":["speedon","roamLikeHome","tns"], "title":"", "hasOffer ...

Reorganizing Elements within an Array using JavaScript

Imagine I have the characters: H, M, L I want to create sorted arrays like this: var array1 = [ "H", "M", "L", "L", "M", "H" ]; My goal is to avoid having more than one unique character in the first three and last three characters when using the shuffl ...

Ways to incorporate javascript in ejs for verifying the existence of a value in an array

I have a products document containing an array of objects with user IDs. When rendering a page, I need to check if the logged-in user's ID is in that array. If it is, I want to display something different compared to users whose ID is not in the array ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Enhancing User Experience with Real-Time Control Updates using ASP.Net and Bootstrap

I am struggling to figure out how to update bootstrap controls with ASP.Net. Here is the code I am working with: @{ Layout = null; } <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width ...

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...

Avoid utilizing the org.json library that comes pre-installed with Android devices

In my project, I have developed a library that relies on org.json (A) from json.org. Android also has its version of org.json (B), but it lacks some important features. I want to configure my gradle so that my project utilizes org.json (A) instead of Andro ...

The function is not being executed when using $scope.$apply()

I am in need of a customized click directive that can execute the passed code using scope.$apply(). $(elem).on('click', function(){ scope.$apply(attrs.wdClick); }); Everything works smoothly when I pass something like wd-click="something = ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...