Guide to populate Div content using JSON information

I am working with a JSON object that contains arrays, and my goal is to dynamically populate a div element.

  • I have a dropdown menu (select option) that I want to fill with all the keys from my JSON data.
  • Each key in my JSON has an array of data as its value. I am attempting to display these values in another div, but it's not working as expected.

Code

$(document).ready(function() {
  var ImageData = {
    "Employ A": [
      "EmployA1.jpg",
      "EmployA2.jpg"
    ],
    "Employ B": [
      "EmployeB1.jpg"
    ],
    "Employ C": [
      "EmployeC1.jpg"
    ]
  }
  var CountersName = Object.keys(ImageData)

  let dropdown = $("#counterNames")
  dropdown.append('<option selected="true" disabled>Select Counter</option>');
  for (var i = 0; i < CountersName.length; i++) {
    $('<option/>').val(CountersName[i]).html(CountersName[i]).appendTo('#counterNames');
  }
  $("#counterNames").on('change', function() {

    var value = $(this).val();

    $(".card-header").text(value); // setting card header 
    console.log(ImageData[value]); // this shows undefined on console
    $(".list-group-item").text(ImageData[value]);


  })

});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}

/* CSS code for switch/slider */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <!-- HTML code goes here -->
</div>

On change of select field for Employee: Displaying specific data based on selection.

.switch {
  <!-- CSS for switch slider goes here -->
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <div class="col-md-6">
    <!-- Card content goes here -->
  </div>
</div>

I have tried the following code:

Object.keys(ImageData).forEach(function (k) {
    ImageData[k].forEach(function (d) {
        console.log(d);
    });
});

Currently, when selecting any option from the dropdown, all values are printed out. However, I intend for only the corresponding values to be displayed based on the dropdown selection (e.g., showing EmployA1.jpg and EmployA2.jpg when selecting 'EmployA').

Answer №1

The usage of the index in the 'ImageData' array is incorrect. It should be written as ImageData['value'] instead of ImageData.value.

Furthermore, there is an error in the following code snippet:

$(".list-group-item").text(ImageData.value)

If you want to display a list of image names, use the code below:

$(document).ready(function() {
  var ImageData = {
    "Employ A": [
      "EmployA1.jpg",
      "EmployA2.jpg"
    ],
    "Employ B": [
      "EmployeB1.jpg"
    ],
    "Employ C": [
      "EmployeC1.jpg"
    ]
  }
  var CountersName = Object.keys(ImageData)

  let dropdown = $("#counterNames")
  dropdown.append('<option selected="true" disabled>Select Counter</option>');
  for (var i = 0; i < CountersName.length; i++) {
    $('<option/>').val(CountersName[i]).html(CountersName[i]).appendTo('#counterNames');
  }
  $("#counterNames").on('change', function() {

    var value = $(this).val();

    $(".card-header").text(value); //setting card header 
    console.log(ImageData[value]); // this shows undefined on console
   //  $(".list-group-item").text(ImageData[value])
   var ul = document.getElementById(".list-group");
   ul_innerhtml = "";
    for (i=0; i < ImageData[value].length; i++) {
    title = ImageData[value][i];
     var ul_innerhtml = ul_innerhtml+'<li class="list-group-item">'+title+'<label class="switch "><input type="checkbox" class="success"><span class="slider round"> </span></label></li>';
    }
    $(".list-group").html(ul_innerhtml);
    
  })

});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}


/* Hide default HTML checkbox */

.switch input {
  display: none;
}


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input.success:checked+.slider {
  background-color: #8bc34a;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

</head>

<body>

<div class="container">
  <div class="col-xs-12 col-sm-12 col-md-6 col-lg-4">
    <label for="counterNames">Select Counter:</label>
    <select class="form-control" id="counterNames">
    </select>

    <div class="card" style="margin: 50px 0">

      <div class="card-header"></div>

      <ul class="list-group list-group-flush">

        <li class="list-group-item">
        <label class="switch "> 
        <input type="checkbox" class="success">
        <span class="slider round">
        </span>
        </label>
        </li>

      </ul>
    </div>
  </div>
</div>

</body>
</html>

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 best way to retrieve an array element from outside a function?

Is there a way to access the distance and pos elements outside of the function in this code snippet? navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longit ...

Can the text color in Grid View columns be customized according to the search item entered?

Please note: The need for changes in various columns will depend on the search request. ...

Is an Ajax call live function needed?

In the sidebar of my website, there is a small box that gets populated using ajax. There are 2 ajax functions set up: one to add items to the list and the other to delete them when the user clicks on the delete button. The HTML structure for this list is q ...

What sets apart an exception from a promise left unfulfilled?

As I delve into the topic of error handling, I came across an interesting concept in my reading material. The literature explains that if a throw statement occurs within a Promise's catch function, it is considered a rejection. It draws a distinctio ...

The second picture in the slider transitions smoothly into view over the visible area of the first image

My image slider is based on jQuery but I'm facing a problem. When the page loads or reloads, the second image of the slider appears in the visible area overlapping the first image like this: https://i.sstatic.net/osbfb.png However, if I click the ar ...

When you try to log a DOM object in a content script for a Firefox WebExtension, it will display "<unavailable>" as the

Working on developing a browser extension using the WebExtension API in FireFox. Currently, while writing a content script, I've encountered an issue where any DOM object passed into console.log results in the string <unavailable> being displaye ...

Why doesn't the HTML tag function inside a <textarea> element?

Check out this code snippet: <textarea rows='15' cols='90' name="activities"> <?php echo "<p style='color: green;'>text area is here</p>"; ?> </textarea> The current output is <p ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Confirmation dialog with user-defined button text

When the confirm prompt box is used, it typically displays "ok" and "cancel" buttons. I am looking to customize the label text for the buttons to read as Agree and Not Agree instead. If you have any suggestions on how to achieve this modification, please ...

Plugin initialization cannot occur as the $scope DOM elements are still dynamic and not ready

As I venture into the realm of AngularJS, this project marks my first deep dive into building something substantial, despite having only tinkered with a few tutorials and demos. Bear with me if I struggle to articulate what may be a straightforward questio ...

Chrome successfully handles cross-domain AJAX calls with Windows authentication, whereas Firefox encounters issues with the same functionality

I am facing an issue with my WCF service that uses windows authentication. When I call this service using ajax in Google Chrome, everything works perfectly as the credentials are cached. However, in Firefox, I am receiving a 401 unauthorized error. I would ...

Support for both Fetch API and XMLHttpRequest across browsers is imperative for seamless data retrieval and

Currently, I am diving into the world of ajax programming techniques. However, I recently discovered that the XMLHttpRequest is deprecated and now I must transition to using the Fetch API. The catch is, according to MDN, the Fetch API is still considered e ...

Error message: Unexpected token discovered, Functioned correctly on Windows yet encountering issues on the VPS. Any suggestions for resolving this?

Challenge: After transitioning my code from a Windows machine to a VPS, everything was working fine on my PC. However, upon migrating to the VPS, I encountered the error listed below: /root/node_modules/discord.js/src/client/Client.js:41 } catch { ...

What is the best way to assign a unique color to two overlapping cells in an HTML table using HTML and jQuery?

I have a task to highlight a row or column when a checkbox is selected, similar to the example shown in the image below. How can I adjust the code so that the overlapping cell gets a different color instead of green or yellow? For instance, in the image b ...

Selecting the parent span element using jQuery

Is there a better way to display text in the parent <div>'s <span>? I'm having trouble with using spans and .parent(), any advice would be appreciated. HTML: <div> <span></span> <!--the span where I need to show ...

Resolving the Angular5 (Angular Universal) problem with page source visibility

Currently tackling a server-side rendering project, inspired by the Angular Universal guide. Everything seems to be on track, but I'm facing an issue where even when navigating to different routes, the source code for the initial page is displayed whe ...

The Skeleton-Avatar and ImageButton components in MUI React have had their backgrounds reshaped into perfect ovals

I am facing an issue with the mui Stack where all the background shapes of the Skeleton Avatar and background area are turning into oval or ellipsoid shapes. I have tried setting equal width and height for Avatar but it has not solved the problem. Is ther ...

Python code to extract text data from a table using XPath

Recently, I've been using requests and lxml to develop a simple API that can fetch a timetable from a specific website. However, being new to this, I'm struggling to extract any information beyond the hours. Despite experimenting with xpath code ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

Trouble with loading Google chart data from a local JSON file

The Issue Running multiple charts on a site simultaneously is causing page blocking while loading all the data before rendering the charts. The goal is to trigger the render function for each chart as soon as the data is available, rather than waiting for ...