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').