Using JavaScript to populate a child dropdown based on data retrieved in JSON arrays

I have been searching for a solution to my simple problem. I want to populate a child combo box in index.jsp after an onchange event in the parent combo box. I have tried using JSON array objects to retrieve the data, but the child combo box is not populating. Can someone please help me? When I select ABC, I want 001 to automatically populate in the second combo box. Similarly, when I select PQR, I want 002 to be populated and 001 to be removed.

index.jsp

 <script type="text/javascript">
 $(document).ready(function() {
 $("#combobox1").change(function() {// by onchange event in parent combo box i want to populate 
 child combobox 
$.getJSON('state.jsp', {count : this.value}, function(responseData) {
$("#combobox2").append(
$("<option></option>").html(responseData.name).val(responseData.name)
);
});
});
});          
</script>

 <body>  
//parent combo box
<select id="combobox1" name="count">
<option value="abc">ABC</option>
<option value="pqr">PQR</option>
</select>
 // child combo box

<select id="combobox2" name="combobox2">// here i want to populate data `001` by `ABC` or `002` by selecting `PQR` , how can i do it?
<option value="">select</option>
</body> 

state.jsp

 <%@page import="net.sf.json.JSONObject"%>
 <%@page import="net.sf.json.JSONArray"%>
 <%
 String count=request.getParameter("count");
 if(count.equals("ABC"){
 JSONObject arrayObj= new JSONObject();
   arrayObj.put("name","001");// how to populate `001` in an option in child combo box when `ABC` will be selected in parent combo?
  response.setContentType("application/json");
  response.getWriter().write(arrayObj.toString());
}
else if (count.equals("PQR"){
 JSONObject arrayObj= new JSONObject();
arrayObj.put("name","002");// how to populate `002` in an option in child combo box when `PQR` will be selected in parent combo?
  response.setContentType("application/json");
  response.getWriter().write(arrayObj.toString());
}
%>

Answer №1

In the instance of my code example provided in Clearing previous options from child drop-down when data is received via JSON

It is important to perform a case-insensitive comparison of the count field (as demonstrated by the original poster in another thread) since the values being passed back are either:

  • abc
  • pqr

and you are currently checking for:

  • ABC
  • PQR

The intended data does not match the existing criteria, causing no results to be returned for the second combo box.

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

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

Can one connect to a Rails database using an iOS application?

Can a database be created using rails and then accessed through both the web application and an iOS application? ...

How to change the color of a row in Jquery selectize using its unique identifier

Is it possible to assign different row colors for each value in the jquery selectize plugin? I would like to set the row color to green if the ID is 1 and red if the ID is 0. This is my selectized field: var $select = $('#create_site').selecti ...

lowdb only modifies a single piece of information in the JSON file

When updating a JSON file with a lowdb request, only the date gets updated. Upon logging the information to be updated, this is the desired update: res.on("end", function () { let body = Buffer.concat(chunks); let final = JSON.parse ...

Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage: <select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br> I'm curious if there ...

Is there a way to add external navigation controls for the Nivo Slider using raphaeljs?

Looking to create a slideshow with interactive next and previous buttons. Utilizing NivoSlider for the smooth transitions, along with raphaelJS for dynamic button animations. The main challenge I'm facing is how to link my custom triangle element to N ...

Finding the root cause of the error message 'Unexpected character: :' from using rjson

My company recently acquired a JSON data set, and I need to extract specific information from it. However, when attempting to import the data using the "fromJSON" method, I encountered an error as described in the title. With over 16,000 files worth of d ...

Issue with Angular's ng-show failing to display an image post-processing

$scope.showProcessedGraph = function(hash) { if ($scope.selectedFile.hash == hash) return; $scope.graph = ""; $scope.isImageLoaded = false; $scope.isLoading = true; if (hash) { $http({ m ...

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

Is there a way to retrieve data from Apollo-Server in nodeJs without relying on React?

Is there a way to fetch data from Apollo-Server (GraphQL) without using React? I tried using node-fetch based on some tutorials but it didn't work as expected. Here is the code snippet I used for fetching data: const getData = (query)=>{ return fe ...

MQTT.js experiencing issues within a Vite environment (React with TypeScript) and a Next.js application

Node version: 18.17.1 Npm version: 9.8.1 I have successfully installed the mqtt package using the following command: npm install mqtt The installation is working perfectly without any issues. Here is a snippet of the code: import { useState } from ' ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

Transforming a string into the date input type layout

I am working with an HTML input type of "datetime-local" that I save in a Datetime field within a MS SQL Server database. Upon loading the edit page, I aim to populate this HTML date field with the value retrieved from the database. Upon examining the va ...

A guide to declaring functions based on certain conditions

I am looking to assign a function that is the result of a ternary operator, which in turn calls one of two functions. The code snippet I have written so far is as follows: const action1 = (x: number) => { // do something ...

Is the CSS code example provided on the JSXGraph website functioning correctly?

I did my best to replicate this example from the JSXGraph website: Below is the condensed HTML: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Covid Sandbox</title> < ...

Using Selenium to send jQuery code from within an iframe

As an avid user of Selenium Webdriver for Python to automate tasks at work, I've been honing my skills by writing scripts in my free time. While attempting to create a bot for neopets.com's Trudy's surprise slot game, I encountered a scenari ...

What is the proper way to perform date validation using the moment library in JavaScript?

I am facing an issue with the departure date validation on my website. I have a textbox called txtDepartureDate where users can choose the date of departure. The requirement is that if the selected date is before today's date, an error message should ...

Tips for condensing a list of dictionaries with varying attributes

Previously, I utilized a straightforward code to retrieve location data from an API, flatten the response, and convert it into a flat dataframe/table. It was effective due to the consistent values and order of the "ExtendedAttributes" key. However, there w ...

The initial request is replaced by new information

Trying to fetch data for autocomplete in Laravel. Controller: public function collection_search(Request $request) { $term = $request->search; $serveurapObj = new Serveurap(); $result = $serveurapObj->collectionAutocomplete(); ...

PHP is encountering a duplication issue with the JSON output

My current goal is to store the JSON return result into a TXT file. However, I am encountering an issue where each iteration in the array includes all previous numbers. For instance, the first iteration only takes the first number in the array $array_1, bu ...