Instructions on implementing getJSON in this code

I recently set up a chained select box with JSON data to populate options, using this Fiddle. While the data is hardcoded for now, I am looking to load it using the $.getJSON() method. However, despite my efforts, I haven't been able to get the code right - there seems to be some issue triggering the suggest.json file. Can anyone help me troubleshoot this problem?

I found the initial dropdown code on this site

The original code snippet:

<script type="text/javascript">

var s = '[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]';


var jsonData = $.parseJSON(s);

var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {    
    var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
    $select.append($option);
});

jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});

</script>

My unsuccessful attempt at modifying the code:

  <script type="text/javascript">

  $.getJSON('suggest.json', function(data){

  var $select = $('#mySelectID');

  $.each(data, function (index, o) {

  var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
    $select.append($option);
  });

  });
  jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});
  </script>

suggest.JSON content:

[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]

Answer №1

If you want to fix the issue, make sure to only call

$("#mySelectID").dynamicDropdown({"delimiter":"|"});
after receiving the data from getJSON.

In your code, simply change the order of the plugin call like this:

$(document).ready(function(){
    $.getJSON('my.json', function(data){

        var $select = $('#mySelectID');

        $.each(data, function (index, o) {
            var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
            $select.append($option);
        });

        $("#mySelectID").dynamicDropdown({"delimiter":"|"});

    });
});

Additionally, there appears to be an error in your JSON as the last item (South America) has "Code" instead of "CODE" like the others.

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

Count the amount of exposed items in each row within a specific container size and dimensions

I created a code sample available at demo code to showcase li elements within a ul displayed in a flow-like manner with the use of display:inline. The challenge I am facing is determining the number of complete li items that are not wrapping for each row ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

Sending JSON data stored in $scope using AngularJS with AJAXPOST request

I am frustrated: I am currently working on an AngularJS project and struggling to correctly post data. I have filled out some HTML input fields, with values stored in a variable like $scope.product, and now I need to send this JSON structure of $scope.pro ...

Utilizing Node.js with Graphics Magick to generate high-quality cropped thumbnails without sacrificing image resolution

Is there a solution to maintain image quality when cropping and centering an image using Graphics Magick? The code I currently have reduces the fidelity of the resulting image. gm(imagePath) .thumbnail(25, 25 + '^') .gravity('Cent ...

Efficiently uploading images with AJAX when submitting a form

I am attempting to upload an image along with other variables in a form submission, and then execute my PHP code to store the image in the user's profile_picture table. I want the image upload to be integrated within the same form used for saving dat ...

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

What is the process for obtaining a JSON structure that represents a Mongoose schema?

Currently, I am working on creating an API in Express and utilizing Mongoose for my data layer. My goal is to make the API as self-explanatory as possible so that the frontend can automatically create forms and validations based on the schema rules establi ...

Decoding PHP Webservice Output on Android

I am currently working on consuming a PHP Web service using JSON in an Android app. After making a request to the server, I received the following response data: string(170) "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19" ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

Scrolling automatically

I'm experimenting with creating a typing effect using JavaScript and the typed.js library, found here: My approach involves using a div as a container. However, I've encountered an issue - when the text reaches the height of the div, scroll bars ...

having trouble adjusting the width of the buefy modal

Currently, I am working with vuejs alongside bulma and buefy. Specifically, I am utilizing the buefy modal feature and attempting to customize the modal width by utilizing its 'width' property. Thus far, I have attempted specifying the width in t ...

Tips for executing multiple commands in NodeJS using child_process.exec

NOTE: I checked this question but it didn't provide the answer I needed. In my attempt to design a task runner for Atom, I encountered difficulties when trying to execute multi-line shell scripts. The issue arose when executing the following code: co ...

Tips on converting a JSON array into a strongly-typed C# class instance via deserialization

This question seems quite similar to another one posted here. Despite my efforts to convert the provided solution into C#, I am not a JSON expert and find myself confused. The challenge lies in deserializing the JSON response from the Kraken OHLC endpoin ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

jsoup - locate element and delete it along with the element preceding it

In my Android app, I am working on extracting data from a stock market historical prices table. However, there are certain rows in the table that need to be removed for clarity. Specifically, I am trying to remove a row in the third tr. I have managed to r ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

React ESLint issue detected at a phantom line

When attempting to build in nextjs using next build, an error occurs with references to line 19 (an empty line) and line 33 (which does not exist). Despite updating the version of eslint-plugin-react in my package-lock.json file to ">=7.29.4", ...

Stop the submission of a form in jQuery if a file with the same name already exists

Currently, I am utilizing MVC3 and have a form containing a file upload feature. My goal is to prompt the user for confirmation if the uploaded file already exists on the server. To achieve this, I have implemented a jQuery method within the form submit fu ...