Combining multiple JSON files into a dropdown menu using JavaScript

Can you dynamically add multiple JSON files to a drop-down menu in JavaScript without just pulling out individual values? Let's say we have two JSON files structured like this:

var data = [
  {date: "A", quantity: 2, total: 190, tip: 100, type: "tab"},
  ...
];

var data1 = [
  {date: "m", quantity: 2, total: 190, tip: 100, type: "tab"},
  ...
];

Now, imagine we create two drop-down menus:

<select onchange = "???" id="data" class="wrapper-dropdown">
    <option value="data">data</option>
    <option value="data1">data1</option>
</select>
<select onchange="???" id="total" class="wrapper-dropdown">
    <option value ="190">190</option>
    ...
    <option value ="300">300</option>
</select>

What should be placed instead of "???" to ensure that clicking either drop-down menu will display the filtered value from the selected JSON file on the console?

Answer №1

Check out the Demo on Fiddle

To address your issue, iterate through the selected JSON object and identify the required elements.

Here is the JavaScript code snippet:

for (var i = 0; i < obj.length; i++) {
    if (obj[i].total == total) {
        document.getElementById("json").innerHTML += JSON.stringify(obj[i]);
    }
}

I hope this solution proves to be helpful for you.

Answer №2

Use the following snippet http://jsfiddle.net/FeN7g/

$( "#total" ).change(function() {

    var selectedOption = $("#total").val();
    $.each(dataList, function(index, item) {
        if(item.total === selectedOption) {
            console.log(item);
        }
    });
})

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

Execute a JavaScript function when a form is submitted

Seeking to reacquaint myself with Javascript, encountering difficulties with this fundamental issue. https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/ var name = document.getElementById("name"); function validate() { alert("Your name is " +name); } < ...

Click the button to save numerous images at once

We have added two mask images to the page. https://i.sstatic.net/uAbb7.png When a user clicks on a mask image, a file upload dialog box appears, allowing the user to upload their own image and click save. https://i.sstatic.net/V4kFA.png After clicking ...

Using Redux and Typescript with functional components: the imported component depends on props provided by Redux

I'm currently working on a component that has the following structure: It features an interface with a "alerts" property It's connected to Redux and receives the "alerts" from props ...

What causes a CSS class to not be applied when using JavaScript onload?

I've been attempting to add a class to an element after the page has loaded in order to change its height and opacity through a transition effect, but so far, I've been unsuccessful. This is how my HTML file looks: <head> <script> ...

The script for Angular2 index.html cannot be included because it is not found

My index.html file looks like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Rock Star Messenger</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-sc ...

Issue with displaying Modal in ReactJS using hooks

I am currently utilizing react hook and react portal to create and display a modal. Here is the code snippet: Modal.tsx const modalRoot = document.getElementById('modal'); const Modal: React.FC<Props> = memo(({isOpen, toggle, children}) = ...

The process of importing jQuery into a project involves importing

I have a website with jQuery and JavaScript functionality. I am including the necessary libraries in the head section of my HTML page: <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" ...

Ensure that all divs have the same height and padding when resizing

I have 3 divs nested within a parent div. My goal is to dynamically set the height of all the child divs to match the height of the div with the maximum height, even when the screen resizes due to responsiveness. Below is my HTML structure: <div class ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

Issue with incremental static generation in version 13 not functioning as expected

Is ISR working for anyone in the NextJS 13 Beta version? I have set revalidate to 15 as follows. export const revalidate = 15; However, even after running `npm run build`, the page still remains a statically generated site (SSG). The symbol is showing u ...

What is the best way to transfer data between windows using titanium (classic)?

'The code I've written utilizes MyHTTPlink to retrieve information such as Restaurant Name, url, and address. Currently, it lists all restaurant names and urls in a table. Now, I want to figure out how to send the details of a table row to the ne ...

Vue: update data and trigger function upon completion of animation transformation, utilizing animation transformation completion listener

Check out this straightforward Vue example: https://codesandbox.io/s/sleepy-haze-cstnc2?file=/src/App.vue https://i.stack.imgur.com/zboCb.png Whenever I click on the square, it not only changes color but also expands to 200% of its original size with a 3 ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

Next.js throwing an error: TypeError - attempting to read property 'map' of undefined

I am facing an issue with my Next Js project. I have implemented the backend logic to display data, but when I attempt to show all the data using the useEffect hook and the map function, I encounter the following error: TypeError: Cannot read property &apo ...

exploring the realm of creating constants in AngularJS functions

controller.js angular.module('app.main') .controller('MainCtrl', function ($scope, currentUser, addAPI) { $scope.form = {}; $scope.subdomain = currentUser.domainName; $scope.add = function () { addAPI.addAdmin(loc ...

Challenges encountered when adding a fresh entry into a Mongo database with Mongoose

Could someone please clarify why I'm encountering MongooseErrors when trying to connect to my database using localhost:27017, with a buffering timeout after 10000ms? Strangely, this issue doesn't occur if I use 127.0.0.1:27017. Note that I do not ...

What are some ways to update translations that are generated by a Google Translate script?

Currently, I am utilizing Google's translation script and am curious if there is a method to override the translation of certain words. Some words are being translated oddly like: "paket~~POS=HEADCOMP". <script type="text/javascript"> function ...

Getting the element from a dropdown menu using Selenium with Python

Currently facing an issue while attempting to choose multiple elements from a dropdown menu using Selenium in Python. I am working with a Website. Struggling with a recurring Timeoutexception error. I have made attempts to inspect the menu using Google Ch ...

How can I ensure consistency between the type of hashtables produced by ConvertFrom-Json and PowerShell's native hashtables?

I have a JSON file called test.json that has the following structure: { "root": { "key":"value" } } To load this data into PowerShell, I use the following code: PS > $data = [System.String]::Join("", [System.IO.File]::ReadAllLines ...