Display JSON content in a div depending on the selected option value

Seeking a more efficient way to load data from a JSON file based on the user-selected option. Currently, I am using multiple else if statements for each state, but it feels repetitive and cumbersome. Is there a better approach? Here's a snippet of my code:

Example:

<select id='test-select'>
    <option>AL</option>
    <option>AK</option>
    <option>AZ</option>
</select>

Script:

var cities = [];
    $.getJSON('/assets/shared/misc/counties.json', function(json) {
        // pushing json to cities array
        cities.push(json);

        // looping through each item 
        $('.state-names').map(function(index) {

            // loading json data based on select option
            $('#test-select').on('change', function() {
                var target = $('#test-select option:selected').val();
                console.log(target);
                if (target == 'AL') {
                    $('.state-names').text(cities[0].AL);
                } else if (target == 'AK') {
                    $('.state-names').text(cities[0].AK);
                } else if (target == 'AZ') {
                    $('.state-names').text(cities[0].AZ);
                } else if (target == 'AR') {
                    $('.state-names').text(cities[0].AR);
                } // end else if block
            }); // end test select function
        }); // end map function

        console.log(cities);

    }); // end getJSON call

This is just a small portion of the code, but it involves many more options and else if's. Is there a way to simplify this process without repeating so much code? Any assistance is appreciated. If additional details are needed, feel free to ask. Thank you.

Answer №1

To access the data stored in the variable target, you can directly use it as a property name like this:

$('.state-names').text(cities[0][target]);

For more information on working with nested objects, arrays, or JSON, check out this helpful post: Access / process (nested) objects, arrays or JSON

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 URL path while navigating through pages with ajax and jQuery

I have implemented ajax post requests to enable paging on a feed within my website. Upon receiving the post request data, I refresh the page by clearing out previous content and displaying the new data retrieved from the request. In addition to this, I wan ...

hasOwnProperty function yields no results

I need help displaying a table from JSON data. Can someone assist me with the code below? <th> { x.amountForQuantity.filter((remaining) => { return remaining.hasOwnProperty(cost.key); })[cost.key] } </th> ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Utilizing the dynamic pairing of Three.js and CSS3 to bring life to animated 3D objects

I am currently working on a project that involves creating 3D Lego elements and assembling them into a figure using animation. I have successfully modeled the elements in Blender and exported them as .obj/mlt files without any issues. However, when it come ...

Webpack-dev-middleware is serving the bundle on a port that is distinct from the application

Recently, I've been developing a React boilerplate that fully utilizes Apollo-Client and GraphQL. The setup of my application consists of one node process overseeing an Express server on port 3000 to render the app, and another Express server on port ...

What methods can a server use to identify if JQuery Ajax's "withCredentials: true" option was utilized for CORS requests?

Currently, I am working on integrating CORS (Cross-origin resource sharing) into a framework. I understand that when an XMLHttpRequest request is made using Jquery's ajax(...) with the withCredentials property set to true, the server must specificall ...

Retrieve the external JSON file using AngularJS

Attempting to retrieve JSON data using Angular JS has been successful with static data. However, encountering issues when trying to fetch data from an external JSON file. Below is the code and corresponding output: index.html <!doctype html> <ht ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...

Tips for changing between two texts within a button when clicked

Seeking a solution for toggling between two different texts inside a button when making an ajax call, with only one text displayed at a time. I'm facing difficulty in targeting the spans within the button specifically. Using 'this' as conte ...

The value in the textarea will stay unchanged even after the form has been submitted

I recently resolved my previous issue, but now I am seeking advice on how to prevent a textarea from clearing its input after submitting a form. You can view the jsFiddle here: http://jsfiddle.net/rz4pnumy/ Should I modify the HTML form? <form id="for ...

After utilizing a while loop with class objects, make sure to reset them afterwards

I am facing a dilemma due to Js referencing objects. Within my Js "class," I have created a new player with various variables, strings, arrays, and functions to check specific conditions related to those variables. As part of my code, I am running a whil ...

The way jQuery and CSS are rendered in the same browser window can vary depending on whether they are loaded via Django or statically

Experiencing a perplexing dilemma. While viewing a web page created using html, jquery, and css on the same browser but in two separate tabs, I am encountering varying renderings of the page. Scenario 1: Directly loading the html file from the file system ...

Leveraging external JSON data in a Jade template with Node.js

Is there a way to successfully pass a Json Object from XMLHttpRequest to my jade file? I am currently experiencing a blank page display and a 500 internal error being sent by the server for the get method. var express = require('express'); var r ...

What is the best way to retrieve information from a JSON string?

I am currently receiving a JSON object from the backend and I only need the "result" array in my Angular application template variable. { "result":[ {"name":"Sunil Sahu", "mobile":"1234567890", "emai ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...