A guide to iterating through an array using only vanilla JavaScript

I am facing an issue with populating a dropdown list depending on the value selected from another dropdown. My goal is to accomplish this using vanilla JavaScript instead of jQuery. I need the second dropdown to be populated with sample data provided below:

Sample Data:

[{"1":"ABA NORTH"},{"2":"ABA SOUTH"},{"3":"AROCHUKWU"},{"4":"BENDE"},{"5":"IKWUANO"},{"6":"ISIALA NGWA NORTH"},{"7":"ISIALA NGWA SOUTH"},{"8":"ISUIKWUATO"},{"9":"OBINGWA"},{"10":"OHAFIA"},{"11":"OSISIOMA"},{"12":"UGWUNAGBO"},{"13":"UKWA EAST"},{"14":"UKWA WEST"},{"15":"UMUAHIA NORTH"},{"16":"UMUAHIA SOUTH"},{"17":"UMU - NNEOCHI"}]

HTML:

<select name="states" id="profileapplicationform-lga_id">
<option value="">Select one</option>
</select>

JavaScript:

<script type="text/javascript">
    window.onload = function(e){
        var select = document.getElementById("profileapplicationform-state_origin_id");
        select.addEventListener('change', function(){
            // AJAX request here
            /* Implementation goes here */
            
            });
        
    }
</script>

After selecting a value in the main dropdown, although I can see the sample data in the response under the network tab, the dependent dropdown remains empty. Any help would be much appreciated.

Answer №1

There are numerous methods available in pure javascript to achieve this task.

Upon receiving the array of data from a GET request, you can utilize a for loop to go through the data and build an extensive HTML string (htmlToInsert) containing each <option> tag with the relevant data within.


Object.entries() generates an array consisting of arrays corresponding to the enumerable string-keyed property [key, value] pairs directly found on an object.

You can then employ array destructuring assignment to extract the key and value pair.

Subsequently, you can easily insert it using Element.insertAdjacentHTML()


It is advisable, for performance considerations, to consolidate all DOM modifications into a single batch, rather than manipulating the DOM within a loop.

const data = [{"1":"ABA NORTH"},{"2":"ABA SOUTH"},{"3":"AROCHUKWU"},{"4":"BENDE"},{"5":"IKWUANO"},{"6":"ISIALA NGWA NORTH"},{"7":"ISIALA NGWA SOUTH"},{"8":"ISUIKWUATO"},{"9":"OBINGWA"},{"10":"OHAFIA"},{"11":"OSISIOMA"},{"12":"UGWUNAGBO"},{"13":"UKWA EAST"},{"14":"UKWA WEST"},{"15":"UMUAHIA NORTH"},{"16":"UMUAHIA SOUTH"},{"17":"UMU - NNEOCHI"}]


let htmlToInsert = ''

for (let i = 0; i < data.length; i++) {
  const [[key, val]] = Object.entries(data[i])
  htmlToInsert += `<option value="${key}">${val}</option>`
}


const select = document.querySelector('#profileapplicationform-lga_id')
select.insertAdjacentHTML('beforeend', htmlToInsert)
<select name="states" id="profileapplicationform-lga_id">
  <option value="">Select one</option>
</select>

Answer №2

Check out this line:

html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';

You cannot access items from objects by index, but you can utilize

data[key] //returns value

This is how your code should be structured

html+= '<option value="' +Object.keys(data[i])[0]+ '">' +data[i][Object.keys(data[i])]+ '</option>';

Object.keys(data[i])[0] first fetches the keys of data[i]. Since there is only one key, you can simply grab the first element of the returned array as your key.

data[i][Object.keys(data[i])] retrieves an element. It then makes use of the data[key] property to obtain the value of that element.

Instead of using list.append(), consider using list.innerHTML += html

Answer №3

After reviewing your sample data more closely, it seems that using Object.entries is the best approach to access both the key and value of each object:

const info = [{"1":"ABA NORTH"},{"2":"ABA SOUTH"},{"3":"AROCHUKWU"},{"4":"BENDE"},{"5":"IKWUANO"},{"6":"ISIALA NGWA NORTH"},{"7":"ISIALA NGWA SOUTH"},{"8":"ISUIKWUATO"},{"9":"OBINGWA"},{"10":"OHAFIA"},{"11":"OSISIOMA"},{"12":"UGWUNAGBO"},{"13":"UKWA EAST"},{"14":"UKWA WEST"},{"15":"UMUAHIA NORTH"},{"16":"UMUAHIA SOUTH"},{"17":"UMU - NNEOCHI"}]

info.forEach(item => {
  for (let [key, value] of Object.entries(item)) {
    output += `<option value="${key}">${value}</option>`;
  }
});

Answer №4

Is something along these lines correct? (written in pure JavaScript)

window.onload =()=>
  {
  const select     = document.getElementById("profileapplicationform-state_origin_id")
    ,   selectList = document.getElementById("profileapplicationform-lga_id")
    ;
  select.oninput =()=>
    {
    selectList.innerHTML = '<option value="">Select one</option>'
      ;
    fetch ( baseurl,  // ??
      {
      method: 'POST',
      headers: new Headers(),
      body:JSON.stringify({state_origin_id: select.value})
      })
    .then ( resp => resp.json())
    .then ( data =>
      {
      data.forEach(elm=>
        {
        let [key, val] = Object.entries(elm)[0]
        selectList.add(new Option(val,key))
        })
      })
    .catch ( err => console.log(err) )
    }
  }

Learn more about JavaScript fetch -> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Explore new Option in JavaScript -> https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option

Any additional questions?

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

Creating a hierarchical navigation menu in CodeIgniter using a single database table

Hello everyone, I'm currently exploring CodeIgniter and attempting to set up a multi-level menu. Below is the structure of my mega menu: ________________________________________________________________________ | main menu | main menu | mai ...

Errors encountered when using Input onChange with React and TypeScript: jsx no-lambda and no-bind issues

While creating a demonstration for a simple task, I encountered some challenges with the taskNameInput component. Despite my attempts, I kept encountering errors. How can I resolve these issues in React when using Typescript? You can refer to my GitHub re ...

Utilizing Angular JS to parse JSON data and showcase it in various tables

Just diving into Angular JS and looking for some guidance. Can someone show me how to parse and showcase JSON Data in separate tables using Angular JS? [ { "id": 0, "isActive": false, "balance": 1025.00, "picture": "htt ...

Tips for avoiding issues with double quotes when working with JavaScript and JSON

Creating a specific String format in JavaScript for JSON might be tricky. The goal is to generate a string like this: ["PNG","350x150","127 KB"] Here's the code snippet using string variables: var imgType = getImageType(); // Returns "PNG" var im ...

Update the withCredentials property to utilize the latest ES6 integrated HTTP request tool known as Fetch

What is the correct way to set withCredentials=true for a fetch promise return? fetch(url,{ method:'post', headers, withCredentials: true }); It seems like the MDN documentation covers everything about http-requesting, except for the u ...

Two jQuery event handlers with similar functionality are displaying distinct behaviors

I've encountered an issue with two identical document fragment objects where separate event listeners are attached using jQuery, as demonstrated in this fiddle. Although the two event listeners should function the same way, only the first one behaves ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

Example code demonstrating how to include an annotation or note using Javascript

I need help developing a feature in an HTML file that I'm opening with Webkit. The goal is to create an app where users can select text and mark it as a note by clicking a 'Note Text' button. After pressing the button, I want a note image t ...

I need to figure out how to incorporate a specific feature into my personal list by leveraging Javascript

Looking at the list below, it's a simple one that allows users to add and remove items while also changing their order using buttons. However, I want to enhance this feature by removing the "up" button for the first item and the "down" button for the ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

Creating hyperlinks in JSON response from a REST API with AngularJS - A guide!

I have a web application built with AngularJS, JS, JQ, and HTML5. This app can send various HTTP methods to the project's RESTful Web Service and receive responses in JSON format. The response is structured like this: When displayed in a <pre> ...

Error Encountered: Nested textarea not supported in HTML

Below is the code I am working with. The issue lies with the <textarea>. In my form, there is a textarea. When I insert another <textarea> within the ckeditor value (HTML), the inner textarea ends up closing the parent textarea. Is there a sol ...

Transferring Arrays from PHP Script to JavaScript Script

Can someone help me figure out how to pass an array from my PHP file to a JavaScript file? Here is the array I have: $pictures = array( "1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"), ); In my JavaScript file, I ...

What is the method for updating the value of a character using a function in JavaScript?

I'm currently working on a function that is designed to take in a character and output a corresponding digit. Below is the code I have written: function getNumber(char) { if (char == "A"||"a") { return char = 5 } else if (char == "B"||"b") ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

I am curious about the significance of ":op?" in a URL route

Reviewing some Node.js Express code, I came across the following route list: app.all('/user/:id/:task?', user.load); app.get('/user/:id', user.view); app.get('/user/:id/view', user.view); app.get('/user/:id/edit', u ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Ways to set up information without altering the original

Is there a way to set Vue data "settings" to be equal to another object "original_settings" without altering the original object when "settings" is modified? How can this be achieved? new Vue({ el: "#app", data: { settings: original_sett ...

Extract the HTML content from the existing UIWebview

My UIWebview displays links that, when clicked, send JSON data. To show this data, I need to: 1) Detect when a link is clicked 2) Retrieve the JSON To retrieve the JSON, I tried using [webView stringByEvaluatingJavaScriptFromString:@"document.body.inner ...