Utilize JavaScript associative arrays to dynamically populate a dropdown menu, followed by automatically filling in a text

As a newcomer to Javascript (although I have a strong grasp of php), I'm experimenting with using associative arrays to accomplish two tasks.

The first task is successfully populating a dropdown menu:

var select = document.getElementById('FName');
var options = fNames;
for(var i = 0; i < (options.length-1); i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}

The 'fNames' variable consists of an array of strings sourced from a php array. Additionally, there is another array named 'fDesc' that is structured to align with the 'fNames' array as follows:

var fNames = ["aName", "bName", "cName"]
var fDesc = ["aDesc", "bDesc,", "cDesc"]

At present, these are distinct arrays rather than a single multidimensional array.

I am looking for a method to display "aDesc" in a text box upon selecting "aName" from the dropdown menu. How can this be achieved?

Answer №1

To start, the for loop in this code is excluding the last element in the array unnecessarily. You should remove the -1 from (options.length-1)

Additionally, you need to add an event handler for the select.onchange and use indexOf to get the index of the selected item in the array.

Here is the HTML structure:

<select id='FName'></select>
<input id='AName' type='text'/>

And here is the JavaScript code:

var fNames = ["aName", "bName", "cName"];
var fDesc = ["aDesc", "bDesc,", "cDesc"];
var select = document.getElementById('FName');
var options = fNames;
for(var i = 0; i < (options.length); i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}

    select.onchange = function(){
        var textbox = document.getElementById('AName');
        textbox.value = fDesc[fNames.indexOf(select.value)];
    }

You can view the code on JsFiddle: http://jsfiddle.net/dBtUz/

Answer №2

It is recommended to display aName as text and use aDesc as the value.

Markup

<select id='Fruit' onchange='fillInfo()'></select>
<input id='Description' type='text'/>

JavaScript

window.onload = function(){
    var fruits = ["Apple", "Banana", "Cherry"]
    var descriptions = ["aDesc", "bDesc", "cDesc"]
    var select = document.getElementById('Fruit');
    for(var i = 0; i < (fruits.length); i++) {
        var el = document.createElement("option");
        el.textContent = fruits[i];
        el.value = descriptions[i];
        select.appendChild(el);
    }
    select.selectedIndex = -1;
}

function fillInfo(){
    document.getElementById('Description').value = document.getElementById('Fruit').value;
}

Answer №3

To retrieve the desired value from an array, you first need to find its index and then access that same position in the array.

Here is an enhanced solution with manual data input:

<script>

    document.addEventListener('DOMContentLoaded', onDomContentLoaded);

    // Data
    var fNames = ["John", "Doe", "Jane"];
    var fDesc = ["Engineer", "Accountant", "Doctor"];

    function onDomContentLoaded() {

        var mySelect = document.getElementById("mySelect");
        fillSelect(mySelect);

        mySelect.addEventListener('change', onSelectChange);
    }

    function fillSelect(mySelect) {
        for(var i = 0; i < (fNames.length); i++) {
            var opt = fNames[i];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
            mySelect.appendChild(el);
        }
    }

    function onSelectChange(){

      var selectedValue = this.options[this.selectedIndex].value;

      var selectedValueIndexInArray = fNames.indexOf(selectedValue);
      var fieldOutput = document.getElementById("output");
      fieldOutput.innerHTML = fDesc[selectedValueIndexInArray];
    }

</script>

<select id="mySelect"></select>

<div id="output"></div>

See it in action here: http://jsfiddle.net/x92ka/4/

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

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

When using Material UI Autocomplete, the selected option should automatically be populated in the input field

When a user navigates through the choices using the arrow keys on their keyboard, I extract the value from the highlighted option to update the current input value (which has its own state). However, when the title or value of the option is saved as the i ...

Unusual behavior experienced with raycasting in Three JS when objects are are repositioned

Software Versions THREE.ObjectLoader2: 2.4.1 THREE.LoaderSupport.MeshBuilder: 1.2.1 THREE.LoaderSupport.WorkerSupport: 2.2.0 THREE.WebGLRenderer: 93 THREE.REVISION: 93 Anomalies Discovered During a raycast operation on objects within my scene, I encount ...

Identifying a particular pattern in a JavaScript string

What is the best way to check if a JavaScript String includes the pattern: "@aRandomString.temp" I need to verify if the String includes an @ character followed by any string and finally ".temp". Thank you ...

The Express JS route seems to be malfunctioning, as it is returning a 404 error for unknown reasons

I have a link that's supposed to direct me to a page, but every time I click on it, the address changes correctly, yet I end up with a 404 Not Found error. app.js var express = require('express'); var path = require('path'); ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Creating a new database row dynamically with PHP, JavaScript, and AJAX

There is a button that triggers a popup box with a textfield when clicked. Once something is entered in the textfield and the "Add" button is clicked, it should be added to the database. Currently, upon clicking "Add", data is inserted into the DB but it ...

An error occurred when trying to set a cookie using Set-Cookie in a react application

Currently, I am immersed in a small project that involves user authentication via email and password before gaining access to their individual profiles. The backend operates on cookies which are established once the correct email and password combination i ...

Encountering a problem with load events in Firefox and Safari browsers

Neither Firefox nor Safari seem to trigger the load event when it's loaded from an external JavaScript file. It appears to only work on Google Chrome. I'm having trouble figuring out the issue. In my HTML: <script src="/assets/js/pages/ ...

What is the best way to avoid adding duplicate HTML content to Bootstrap modal divs using jQuery?

In my project, I wanted to create a functionality where clicking on an image would trigger a modal box to pop up with additional content added once. However, I encountered two issues that I'm currently facing. Firstly, the header text that I intended ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Altering the background color of a button in a navigation bar and mirroring that same color on a linked page when clicked

I'm facing an issue with my asp.net Master page. I have a menu bar with 4 buttons, and I want to change the color when a button is clicked. I was able to achieve this using java script, but the problem arises when I redirect to a child page, as the co ...

Use Material UI Grid to create a horizontal line design instead of focusing on making the

Is there a way to turn off responsiveness for the material UI grid similar to how it can be done with a basic HTML table? While an HTML table scales down and adds a horizontal scroll bar, the material UI grid remains responsive as shown in the example belo ...

Creating an Angular directive that shares a single scope while displaying multiple behaviors

I am facing a specific scenario with my directive where the refresh scope needs to be either an object or a function. How can I properly assign this to my directive? 1. Initial scenario <!--HTML--> <directive refresh="vm.refresh"> </dir ...

When a mobile device is rotated, the screen on a jQuery application will automatically shrink

Having trouble with JQM and device rotation on iOS devices. The screen doesn't resize properly when rotated. I have this line in the header to handle display size: <meta name="viewport" content="height=device-height,width=device-width,initial-scal ...