Tips for showing a value in an input text box

Imagine you have a select tag with multiple options. You want to display a specific value in the input field below when a user selects one of the options.

<select name="cars" id="cars">
  <option value="volvo">Volvo-100</option>
  <option value="saab">Saab-200</option>
  <option value="mercedes">Mercedes-300</option>
  <option value="audi">Audi-400</option>
</select>
<input type="text" id="name" name="name">

If Volvo is selected, the input field should display the value 100. If Audi is selected, the input field should display the value 400. I am in need of assistance with this, can someone please help me?

Answer №1

Feel free to reference this solution for your query.

element.options and element.selectedIndex are the key elements to achieve the desired outcome. You can find more information by visiting this link

const select = document.querySelector('#cars');
const input = document.querySelector('#name');

select.addEventListener('change', function(e) {
  const option = this.options[this.selectedIndex];
  const value = option.text.split('-')[1];
  input.value = value;
})
<!DOCTYPE html>
<html lang="en>
<head>
<title>Title</title>
    <body>
        <select name="cars" id="cars">
            <option value="volvo">Volvo-100</option>
            <option value="saab">Saab-200</option>
            <option value="mercedes">Mercedes-300</option>
            <option value="audi">Audi-400</option>
        </select>
        <input type="text" id="name" name="name" value="100">
</body>
</html>

Answer №2

If you want a simple way to achieve this, you can utilize the change event listener. Make sure to update the value attribute of each option to match the values you specified in your initial question. The selected option can be accessed using event.target.value.

Here's an example implementation:

const selectElement = document.querySelector('#cars');
const textInputElement = document.querySelector('#name');

selectElement.addEventListener('change', event => {
  textInputElement.value = event.target.value;
});
<select name="cars" id="cars">
  <option value="100">Volvo</option>
  <option value="200">Saab</option>
  <option value="300">Mercedes</option>
  <option value="400">Audi</option>
</select>
<input type="text" id="name" name="name">

Additional resources:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Answer №3

  1. Utilize addEventListener function
  2. If the text is present, divide it into parts
  3. Include an additional 0 option to enable selecting Volvo from the beginning
  4. Avoid naming a field name as it is already used elsewhere in the DOM and does not represent a name

document.getElementById("cars").addEventListener("change", function() {
  const text = this.options[this.selectedIndex].text
  const value = this.selectedIndex > 0 ? text.split("-")[1] : "";
  document.getElementById("carNumber").value = value;

})
<select name="cars" id="cars">
  <option value="">Please select</option>
  <option value="volvo">Volvo-100</option>
  <option value="saab">Saab-200</option>
  <option value="mercedes">Mercedes-300</option>
  <option value="audi">Audi-400</option>
</select>
<input type="text" id="carNumber" name="carNumber">

Answer №4

To achieve this functionality, you can utilize the following code snippet:

const [vehicles, model] = ['vehicles', 'model'].map(document.getElementById.bind(document));

vehicles.addEventListener('change', ({
    target: {
      selectedOptions: {
        0: option
      }
    }
  }) => model.value = option.innerText.split('-')[1]);
<select name="vehicles" id="vehicles">
  <option value="toyota">Toyota-Camry</option>
  <option value="honda">Honda-Accord</option>
  <option value="ford">Ford-Explorer</option>
  <option value="chevrolet">Chevrolet-Impala</option>
</select>
<input type="text" id="model" name="model">

Answer №5

Here's how you can solve this problem:

function extractCarName(sel) {
  document.getElementById("name").value = sel.options[sel.selectedIndex].text.split('-')[1]
}
<select name="cars" id="cars" onChange="extractCarName(this);">
  <option value="volvo">Volvo-100</option>
  <option value="saab">Saab-200</option>
  <option value="mercedes">Mercedes-300</option>
  <option value="audi">Audi-400</option>
</select>

<input type="text" id="name" name="name">

Answer №6

You are facing a conflict with identifiers.

I decided to replace the id="name" with xname and included an onchange event as well.

  <select name="cars" id="cars" onchange="xname.value=this.value;">
      <option value="volvo">Volvo-100</option>
      <option value="saab">Saab-200</option>
      <option value="mercedes">Mercedes-300</option>
      <option value="audi">Audi-400</option>
    </select>
    
    
    <input type="text" id="xname" name="name" value="abc">

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

Adding a unique component to a Spring Boot application with Thymeleaf integration

My navigation bar includes a list with a dropdown feature. When the user clicks on the dropdown entry, I want to display a snippet of another HTML page within the project. The navigation bar HTML code is as follows: <div th:fragment="navbar"& ...

html search table td

How can I perform a search in a specific column of a table? Here is the JavaScript script and input tag that I am using: <script type="text/javascript"> function searchColumn() { var searchText = document.getElementById('searchTerm ...

Parallel mapping with simultaneous multiple inserts

I am working on inserting a list of topics with unique slugs into a MongoDB database. Here are two example topics: { title: "my title" }, { title: "my title" } After generating the slugs, I need to insert the topics: // Insert each topic async.map( ...

What is the proper method for running a script using the Selenium JavascriptExecutor?

On my test.html page, I've included the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> ...

Unusual "visual" phenomenon with autocomplete feature in VUE.js

Can someone review this code snippet? Check out the code here This is a peculiar example of a custom autocomplete VUE component. If you enter a value in one of the fields in Section 1 (like 'Apple'), then click on the Next button, you'll ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Having trouble deleting files in PHP?

I am presenting an HTML form below: <form action='delete.php' method='POST'> <table> <div class = '.table'> <?php $dir = '../uploads/store/'; $new ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Is it possible to use a variable in JSX within a map function to modify inline CSS styles?

I have a map function that loops through an array and generates divs on the DOM for each color item. The array consists of hex values representing different colors (e.g. #1a703f). The goal is to set the background of each div to match the corresponding co ...

Coming back from retrieving data from an API

I'm having trouble with a function that performs a POST request to retrieve access tokens from an API. Although the function successfully prints the token to the console, I haven't been able to figure out how to properly parse and save the access ...

Managing redundant asynchronous data in AngularJS

Imagine this scenario: In your AngularJS application, a user is spamming input which triggers numerous asynchronous data calls on the backend. This results in constant changes to the displayed data as each fetch request completes. Ideally, we want the fina ...

Freeze your browser with an Ajax request to a specific URL

There is a function in my view that transfers a value from a text box to a table on the page. This function updates the URL and calls another function called update_verified_phone(). The update_verified_phone() function uses a model called user_info_model( ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

A webpage specified with 'charset=iso-8859-1' accompanied by <!DOCTYPE HTML> is triggering a cautionary alert

After running the W3C validator on an HTML document, I discovered that using the following meta tag: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> in conjunction with: <!DOCTYPE HTML> results in ...

Promise Pending awaiting response from function

Could someone please explain why the code I have written below is returning a Promise pending value for the 'out' variable? var out = dbConn.connect().then(function (){ var request = new sql.Request(dbConn); request.input("termin ...

Issue encountered while retrieving the response, in case the node.js server sends the response with a delay

My aim is to upload an image and have the nodeJS server send the path of that image folder back as a response. Unfortunately, when I try sending the response after completing a task, nothing seems to be happening on the angular-side. Below is my componen ...