developing toggle switches using JSON

I am faced with a JSON containing two keys, "cars" and "others". How can I implement a toggling feature on my website using HTML/CSS/JavaScript such that:

  • Clicking on "cars" displays the car items (small vehicle, large vehicle) in red text.
  • Clicking on "others" hides the car items and displays the other items in blue text.

Please note: The toggle button or link should function properly for switching between the two options.


{
    "cars": {
        "items": ["small-vehicle", "large-vehicle"],
        "color": "red"
    },
    
    "others": {
        "items": ["swimming pool", "plane", "ship"],
        "color": "blue"
    }
}

Answer №1

Below is the code to help you get started.

Upon clicking the appropriate button, it will alert() and display the color of each item.

Now it's your turn to properly figure this out and make it work according to your preferences.

I've included a select list for you to try as well. Run the code and see how it works.

let items = {
"cars": {
"items": ["small-vehicle","large-vehicle"],
"color": "red"
},

"others": {
"items": ["swimming pool","plane","ship",],
"color": "blue"
 }
}

function showMeCarColor(){
  alert(items.cars.color);
}

function showMeOtherColor(){
  alert(items.others.color);
}

function doThing(){
  let selectedItem = document.querySelector("#itemList").value;
  switch (selectedItem){
    case "car":{
      alert(`car is : ${items.cars.color}`);
      break;
    }
    case "other":{
       alert(`other is : ${items.others.color}`);
       break;
    }
  }
}
<button onclick="showMeCarColor()">Cars</button>
<button onclick="showMeOtherColor()">Other</button>

<select id="itemList" onInput="doThing()">
  <option value=""></option>
  <option value="car">Car</option>
  <option value="other">Other</option>  
</select>

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

Searching for a child tag in JSON using C#

Is there a way to retrieve the id value of the child elements in this code using C#? I am currently working with C#. While I am able to extract the result value, I am struggling to access the "id" value from the result. Thank you for your help. var job ...

How can I display only a horizontal scrollbar on the body content while avoiding an excessively long image header?

Currently, I have a 4000px width image as the header of my website. To hide the horizontal browser scrollbar, I am using the following CSS: html { overflow-x: hidden; } However, this method results in the horizontal scrollbar never appearing. I ac ...

Expanding Issue with Bootstrap Navigation

Hello! I am experiencing an issue with my navbar. The menu collapses, but it does not expand. I have used an example from Bootstrap and made some tweaks, but for some reason, it still doesn't expand properly. Below is the code that I have been workin ...

Ways to show text on a donut chart when hovering with the mouse

I have been attempting to make adjustments to this sample. My goal is to display a word in the center of the donut chart upon mouseover, similar to this: https://i.sstatic.net/dCPKP.png Although I have included code for mouseover, it seems to not be func ...

Discovering the best way to organize and sort information retrieved from the backend within an Angular

How can I restrict a user to only search for data that has been provided from the backend and prevent them from creating new data? In my backend, there are two words: "Chart" and "Map". I am looking for a way to limit the user's search to only these ...

Utilize Spark Scala to extract information from JSON documents

Looking to transform the JSON source data file listed below into the Expected Results format as indicated. Wondering if there is a way to accomplish this task using Spark Scala. Any assistance would be greatly appreciated. JSON source data file { "APP" ...

Display interactive form data on webpage post submission utilizing Knockout.js

I am in need of guidance on displaying the content of a form on the same page beneath it. Essentially, I need to fetch the value using document.getElementById() or a similar jQuery method. I am currently experimenting with some code samples I found onlin ...

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

Using axios to render data in a view template

I am currently working on developing a basic Single Page Application (SPA) with the help of vue.js and axioz for scripts, without using CLI or any other tools. At this point, I have succeeded in fetching data from a JSON file, rendering and paginating the ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...

Discovering local establishments using mongoDB and mongoose

I am managing a small database where I manually added places and currently working on filtering them by minDistance and maxDistance. Here is the mongoose schema I am using: var schema = new Schema({ name: { type: String, unique: fals ...

Generating an HTML table using an array retrieved from a PHP execute_db function, displaying repeated entries

My goal is to dynamically populate an HTML table with data retrieved from a SQL query. The structure of the table, including headings, should adjust based on user selections, reflecting the results of the query. While searching for a solution, I came acros ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

Overflow issues with CSS FlexBoxLayout

I am currently working on creating a website using Bootstrap and CSS's flexbox. My goal is to create a list that fits the height of the screen without overflowing it. After some trial and error, I managed to come up with a solution that looks like th ...

Show a specific portion of an extremely large .svg image file using Angular.js directive with the help of javascript or css

Currently, I am facing a challenge with a large map image (3000x8000px) in .png format that I have converted to .svg for data visualization purposes. I am struggling to find a way to display a specific small section of this map.svg file on an HTML page u ...

displaying pictures exclusively from Amazon S3 bucket using JavaScript

Considering my situation, I have a large number of images stored in various folders within an Amazon S3 bucket. My goal is to create a slideshow for unregistered users without relying on databases or risking server performance issues due to high traffic. I ...

create a layout with intersecting divs to display a table/chart

Lately, I have been pondering how to achieve a design similar to the one shown below. Specifically, I am interested in the "sparkline/area" chart that appears at the bottom of the table/divs. I can't seem to figure out how to code something like this ...

Leverage PHP to retrieve information from a JSON file and integrate it into a dropdown menu on an HTML

I've been given a task to develop a PHP routine that will extract the ISO code and name from a geojson file for use in a dropdown list of countries on a website. This is completely new to me and I'm finding it difficult to understand the documen ...

React frontend unable to retrieve JSON data from Rails API

I have developed a backend Rails API and confirmed that the endpoint is being accessed by monitoring my server in the terminal. Additionally, I am able to view the response in Postman. However, I am facing an issue where the payload is not returned in my R ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...