Choose a different option when there is a change

Here is an example of JSON data:

[{
        "user_id": "113",
        "employe_first_name": "Asaladauangkitamakan",
        "employe_last_name": "Nasibb"
    }, {
        "user_id": "105",
        "employe_first_name": "Ryan",
        "employe_last_name": "Friday"
    }, {
        "user_id": "87",
        "employe_first_name ":"hendi ",
        "employe_last_name ":"kenther"
    }
]

How can I dynamically create a select dropdown with JavaScript where the option value is the user_id and text is the employe_first_name, then load this when the document is ready? Additionally, how do I fill another field with the selected value from the dropdown?

Answer №1

let employees = [ {"user_id":"113","employe_first_name":"Asaladauangkitamakan","employe_last_name":"Nasibb"}, {"user_id":"105","employe_first_name":"Ryan","employe_last_name":"Friday"},   {"user_id":"87","employe_first_name":"hendi","employe_last_name":"kenther"} ];
let selectMenu = document.createElement("select");
for(let i = 0; i < employees.length; i++){
    let option = document.createElement("option");
    option.value = employees[i].user_id;
    option.innerHTML = employees[i].employe_first_name;
    selectMenu.appendChild(option);
}
selectMenu.addEventListenter("change", function(event) {
    let selectedValue = event.target.value;
    document.getElementById("another_field").value = selectedValue;
});
someDiv.appendChild(selectMenu); // Append the select menu to the DOM

Answer №2

Give this a shot:

const employeeData = [ {"user_id":"113","employe_first_name":"Asaladauangkitamakan","employe_last_name":"Nasibb"}, {"user_id":"105","employe_first_name":"Ryan","employe_last_name":"Friday"},   {"user_id":"87","employe_first_name":"hendi","employe_last_name":"kenther"} ];
var select = document.createElement("select");
for(let i = 0; i < employeeData.length; i++){
    let option = document.createElement("option");
    option.value = employeeData[i].user_id;
    option.innerHTML = employeeData[i].employe_first_name;
    select.appendChild(option);
}

Check out the DEMO

Answer №3

consider trying a similar approach

// executing on DOM load
var tid = setInterval( function () {
    if ( document.readyState !== 'complete' ) return;
    clearInterval( tid );       
    var json_len = json.length;
    var select = document.getElementById('select_id');
    for(var i=0;i<json_len;i++){
        var option = document.createElement('option');
        option.innerHTML = json[i].employe_first_name;
        option.value = json[i].user_id;
        select.appendChild(option);
    }
}, 100 );

REFERENCE

Is there a way to check document.ready() if jQuery is not available?

Answer №4

If you're looking to incorporate jQuery into your project, here's one way to do it.

Make sure to replace selectId with the actual ID of your dropdown element.

 var employeeData = [{
        "user_id": "113",
        "employe_first_name": "Asaladauangkitamakan",
        "employe_last_name": "Nasibb"
    }, {
        "user_id": "105",
        "employe_first_name": "Ryan",
        "employe_last_name": "Friday"
    }, {
        "user_id": "87",
        "employe_first_name": "hendi ",
        "employe_last_name": "kenther"
    }
];
    var dropdownElement = $("selectId");
    $(employeeData).each(function() {
        $("<option value='" + this.user_id + "'>" + this.employe_first_name + "</option>").appendTo($(dropdownElement));
    });

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

Utilize lodash to trim the object key

I am looking for a solution to remove occurrences of the object key y_ and achieve an output similar to useroutput: var user =[{"data":"2","y_data1":1},{"data":"4","y_data1":3,"y_data2":3}] var useroutput=[{"data":"2","data1":1},{"data":"4","data1":3, ...

Grabbing only the button element using jQuery when a click event occurs

HEY THERE! I have a simple question that I need help with. To better explain the issue, I've included a small code snippet below. The problem I'm facing is related to grabbing the id of a button. Everything works fine except when I click on any ...

Experiencing issues while trying to publish on Cloudflare Workers?

To organize my project, I decided to create a folder named workers. Inside this folder, I followed these steps: Firstly, I initiated the project using npm init. Next, I installed @cloudflare/wrangler by running npm i @cloudflare/wrangler. This action resul ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

Transform your standard HTML buttons into a collective of radio buttons

Looking for a way to make some ordinary buttons function as radio buttons without adding another library to the project. Any suggestions on how this can be achieved using just HTML and JavaScript/jQuery? Appreciate any help, thank you. ...

I need to display 5 columns in a parent component, each with its own unique icon. How can I conditionally render them in a React component?

Creating a parent component to reuse multiple times can be very useful. In my case, I have included 5 different icons in each instance of the component, all taken from hero icons. I have set up an object with unique ids for each child component, but I am ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

As soon as I closed the modal, I noticed that the checked inputs reverted back to

I am using checkboxes within a modal to narrow down my search results. However, I have encountered an issue where when I check multiple checkboxes and then close the modal, the checked inputs become unchecked. Every time I open the modal, I want the check ...

What is the process for importing the TokenExpiredError that is thrown by the verify function in jsonwebtoken?

Is there a way to determine if an Error object thrown by the jwt.verify function in the jsonwebtoken library is of type TokenExpiredError using Typescript's instanceof? For example: import jwt from "jsonwebtoken"; function someFunction() { try { ...

Guide to setting up Gatsby CLI and Gatsby version 2

Currently, I am working on a project that utilizes Gatsby v2 in its package.json file. However, to run the project, I need to globally install Gatsby-cli as per the documentation. Strangely, the global installation of Gatsby-cli also installs Gatsby v4, ca ...

What is the best way to automatically remove a Firebase database entry when a user has been inactive for a period of time, without logging out but simply not accessing the page for an extended duration?

Currently, when a user clicks 'logout', their session is terminated, and a database entry is removed. All other users can see that database entry, so the objective is for users to view each other's data only while they are logged in. For in ...

Whenever I execute the code, my if statement seems to interpret the conditions as true regardless of the actual values

let num = (Math.floor(Math.random() * 6 + 1)) console.log(num) if (num === 6) console.log('Wow, you hit the jackpot with a rarity of 1/6!') The above code snippet generates a random number between 1 and 6, then prints "that was a 1/6 chance" if ...

Sending query strings to jQuery load

I have a website page that dynamically loads data using jQuery.load() based on the selected filters by the user, which could be city, category, or both. To make it work, I implemented onchange events for the two dropdown filters: $('#filter1'). ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

Implement a function in JavaScript to sum quantities for identical JSON objects

I am looking to calculate the total quantity for each category. var items = [ { cat: 'EK-1',name:"test",info:"mat", quantity: 3}, { cat: 'EK-2', name:"test2",info:"na ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

What causes the "Error: method not allowed" message to appear when attempting to send a "DELETE" request from a Next Js component? (The POST method is

This is my first time on this platform, and I'm currently following a tutorial from Javascript Mastery to create a clone of a thread application. After watching the entire video and building the basic functionality based on it, I decided to enhance th ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...