JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack Overflow all displayed alert windows, whereas I want the value to populate directly in the form.

Below is the snippet of my HTML code for the Customer Name dropdown list:

<select id="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>

Here is the mapping between customer names and codes: Doe Inc = 276. Smith LLC = 852. Rogers and Co = 552.

I am seeking a way for the customer code to update automatically when the customer name is changed without requiring a separate button click. This is important as it is part of a larger form that will have a Submit button at the end, eliminating the need for users to click "Submit" twice – once for retrieving the customer code and again later in the form.

Thank you!

Answer №1

For your form controls to be included in a form submission, they must be successful controls, which simply means they must have a name="" value:

<select id="customername" name="customername">
    <option></option>
    <option>Doe Inc</option>
    <option> Smith LLC </option>
    <option> Rogers and Co </option>
</select>

If you want to submit the customer code but display the customer name on the form as well, add the value attribute to your options and rename the select element accordingly:

<select id="customercode" name="customercode">
    <option value="">Select one...</option>
    <option value="276">Doe Inc</option>
    <option value="852">Smith LLC </option>
    <option value="552">Rogers and Co </option>
</select>

If you wish to have both values visible on the form and submitted with the form, you can use a data- attribute to synchronize with a read-only input:

<select id="customername" name="customername">
    <option data-value="">Select one...</option>
    <option data-value="276">Doe Inc</option>
    <option data-value="852">Smith LLC </option>
    <option data-value="552">Rogers and Co </option>
</select>

<input type="text" name="customercode" id="customercode" readonly />

To synchronize them, you can use some JavaScript:

var select = document.getElementById('customername');
select.onchange = function(e) {
  var value = select.options[select.selectedIndex].dataset.value;

  var input = document.getElementById('customercode');
  input.value = value;
}

Check out this example jsFiddle: https://jsfiddle.net/27jx0q3a/3/

Here are some helpful links:

Answer №2

I have customized the solution to meet your needs. I utilized an array to structure the numbers, implemented the onchange function on the select element, and waited for any changes. Once a change is detected, I trigger an event and use Javascript to fetch the field values, compare them with the array, and return the result based on the selected value.

For more detailed explanations and alternative methods for static html, please check out Tieson T.'s response!

var drop_down = document.getElementById("customername");
var result = document.getElementById("result");
var list_array = {
  "": "Please Select A Value",
  "Doe Inc": 276,
  "Smith LLC": 852,
  "Rogers and Co": 552
}

function change_value() {
  if (list_array[drop_down.value]) {
    result.innerHTML = list_array[drop_down.value];
  }
}
<select id="customername" onchange="change_value()">
  <option></option>
  <option>Doe Inc</option>
  <option>Smith LLC</option>
  <option>Rogers and Co</option>
</select>
  
<span id="result"></span>

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

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

What are the drawbacks of relying on a dependent dependency in software development?

In a recent discussion on Stack Overflow, it was suggested that the best practice is to install packages from sub-dependencies for future use in the app, rather than directly from the dependencies node_modules folder. However, my scenario is a bit unique. ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

"Enhancing Forms with Multiple Event Listeners for Seamless Sub

I'm working on creating a countdown timer with 3 buttons for controlling the timer: start, cancel, and pause. The timer itself is a text input field where you can enter a positive integer. I need to use core JavaScript, not jQuery Start Button: Init ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Monitor the traffic on my website by implementing .htaccess restrictions

I am maintaining a website with restricted access to specific IP addresses listed in the .htaccess file. I am looking to implement a logging system that tracks unauthorized attempts to access the site. Is it feasible to record each attempt in a database? ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Troubleshooting problems with displaying views due to asynchronous $http.get calls in AngularJS

Within my application, I am utilizing two separate API calls. The initial call retrieves a catalog of services along with their unique ID's. Subsequently, once the ID information is acquired, a second call is made to retrieve pricing data for each cor ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

execute php function when form is submitted

Hello, I am attempting to create a code using this PHP function: <?php function generateRandomString($length = 6) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/str ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Ways to test the initial launch of an Android application using Cordova

I am developing an Android application using Cordova. My app consists of multiple pages, with the main homepage being index.html. I need to determine if it is the first time a user lands on the homepage after opening the app, regardless of how many times ...

Using PHP to generate a table populated with generic elements from an array

How can I create a dynamic table in PHP that can handle any generic array with different keys and values, including nested arrays? I want to use the same table structure for various arrays regardless of their content. Any advice on achieving this flexibili ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

Vue is removing a DOM node during the created lifecycle hook to set up a component

I am currently working on understanding the issue with this example that is not behaving as expected. My goal is to initialize my ContentView using the server-side rendered HTML in the DOM. I plan to check if init__main-content exists and then initialize t ...