Using Javascript to populate text input fields with selected values from a dropdown menu

I am in need of assistance with a JavaScript task as I am still relatively new to it.

Currently, I have two input text fields that I would like to populate with text based on the selection made from a dropdown menu.

For instance...

The select field looks like this:

<select id="select_2" onchange="insertProduct(2);">

And the options within the select field appear as follows:

<option id="cdrom001" title="my cdrom">cdrom001 - my cdrom</option>
<option id="DVD-ABUG" title="A Bug's Life">DVD-ABUG - A Bug's Life</option>
<option id="DVD-BELOVED" title="Beloved">DVD-BELOVED - Beloved</option>
....

What I am aiming for is that upon selecting an option from the dropdown list, text input field #1 should be filled with the option id (e.g. DVD-ABUG) and text input field #2 should be populated with the option title (e.g. A Bug's Life).

Here is the code for the two text input fields:

<input type="text" name="model[]" id="model_2">
<input type="text" name="product[]" id="product_2">

I have begun writing the function that will be necessary for this task, but I need help:

function insertProduct(id){ 
// code goes here
}

As you can tell, I haven't made much progress. :o)

Could someone provide guidance on how to create the function for this task?

Thank you so much!

Answer №1

Modify the following line:

<select id="select_2" onchange="insertProduct(2);">

to this:

<select id="select_0" onchange="insertProduct(this, 0);">

and implement this function:

function insertProduct(select, row){ 
    var model = "model_";
    var product = "product_";
    document.getElementById(model + row).value = select.options[select.selectedIndex].id;
    document.getElementById(product + row).value = select.options[select.selectedIndex].title;
}

Answer №2

If you're searching for the solution, try substituting the use of onchange for button click.

Check out this link for more information:

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

Order Up: Vue Draggable Next feature keeps your lists in line

I need to maintain the order of two lists in local storage so that their positions are saved and retrieved between sessions. In my Vue 3 TS project, I am utilizing this library. Check out the code snippet below: <template> <div> <h3> ...

Utilize Vue.js functions within data through the Vue.js context

I'm trying to incorporate a function as a data property. While it works for the 'works' data property, I need access to the this context within the function in order to calculate values from the shoppingCart property. Is there a way to achie ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

What benefits does redux-thunk offer?

Why is redux-thunk necessary? It seems like using a thunk just adds an extra layer of complexity by wrapping expressions and using middleware. The sample code from redux-thunk further confuses the process. import thunk from 'redux-thunk'; // No ...

Incorporating Functions from an External Script in ReactJS/GatsbyJS

One of the functionalities on my website involves dynamically inserting a script into the head when a form element is focused, enabling it to load faster. This process is achieved using basic vanilla JS rather than React Helmet, as shown below: const handl ...

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

declaring a variable in JSP and incorporating it into jQuery

How can I retrieve the size of options in a route object and store it in a variable in JSP? I then need to access this variable in jQuery. Any suggestions on how to achieve this? JSP code : <%!int loopSize = routes.get(0).getOptions().size(); %> ...

Ways to select a random row from a MySQL database

<button onclick="myUniqueFunction()">Press here!</button> <?php function myUniqueFunction() { $con = mysqli_connect("mysql.hostinger.no", "u452849516_altge", "password", "u452849516_altge"); $query = "S ...

div value causing erratic behavior in cycling process

Instead of following the normal balance calculation (1000-950), something odd happens and the balance goes from 1000 to 0 with the while loop. I never intended for the refBalance to drop below 0. (numDebit2() returns 50) <div class="elemen ...

What does the HTML and JS code look like when using Next.Js?

Here's an illustration of the desired result: codepen.io/j0be/pen/jWGVvV How can I implement this HTML and JS in Next.js? I am looking to customize this code using TypeScript and SCSS in Next.js. However, I am unsure about how to convert the HTML an ...

Steps for modifying a cell within a table using a button click

Hello, I am currently working on a project where I want to display a specific div portion when a user clicks on an image icon within a table. However, I am encountering an issue with the JavaScript code as it only shows the div portion in the first row and ...

How can I use jQuery to hide each div of the same class individually when a user clicks on each div to close

I am working on a project where I have multiple notification boxes represented by divs with the same class. These boxes are set to fade in one after the other using jQuery. Each box also contains a 'close_box' div that acts as a button to close/h ...

The function was not invoked as expected and instead returned an error stating "this.method is not

I need help with an issue in my index.vue file. The problem lies in the fancy box under the after close where I am trying to call the messageAlert method, but it keeps returning this.messageAlert is not a function Can someone please assist me in resolving ...

What is the best method for encrypting a file using node.js?

I am in the process of finding a way to encrypt various types of files like txt, mp3, or any other file in node.js while utilizing socket.io. My goal is to develop an application that can securely send files to another client, so I wish to encrypt the file ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

Angular's '@angular/core/core' module does not have the exported member 'ɵɵFactoryDeclaration'

My Angular application was successfully compiled after running npm install. However, upon executing npm start, I encountered the following error: ERROR in node_modules/ng-apexcharts/lib/chart/chart.component.d.ts:57:21 - error TS2694: Namespace '&quo ...

Does embedding an Iframe for external files from your server enhance the loading speed of the current page compared to directly loading it on the page?

I'm facing an issue with the loading time of a Facebook post on my webpage index.php. The current method of using the embedded post provided by Facebook is taking too long to load. My solution is to create a separate page, post.php, where only the Fac ...

How to Process a Stripe Payment using jQuery AJAX (JavaScript Only)

I'm in the process of creating a custom payment form for Stripe and I want to manually initiate the AJAX call to connect with Stripe. Instead of relying on a typical submit event. Unfortunately, it seems like I might be sending the request to the inc ...

What is the process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

Shifting Data between JavaScript and PHP

At the moment, I am trying to transfer a variable from JavaScript to PHP. This variable is being utilized for Stripe payment processing. I believe AJAX might be necessary for this task? function _goAheadWithCustomerId(c) { console.log('Customer I ...