JavaScript

Populate Textbox Based on Dropdown Selection – JavaScript

While developing a web application, it is normal to add a form with a drop-down list and a text box. The user can select a value from a number of options using the drop-down list, and the selected value is shown in the text box. For achieving this functionality, use the “change” event with the help of the “addEventListener()” method.

This article will define the procedure to fill the textbox depending on the drop-down selection using JavaScript.

How to Populate Textbox Based on Drop-down Selection in JavaScript?

To populate or fill a textbox based on a drop-down selection, utilize the drop-down’s “change” event that will detect the selected option by the user and set the textbox’s value.

Example
Create a label for drop-down using the HTML element called <label>:

<label>Select a Language You Want To Learn:</label>

Create a drop-down list using the <select> and <option> tags. The drop-down contains the list of languages:

<select id="dropDown">
 <option value="select">Select....</option>
 <option value="HTML">HTML</option>
 <option value="CSS">CSS</option>
 <option value="JavaScript">JavaScript</option>
 <option value="Java">Java</option>
 <option value="Python">Python</option>
</select>

Here, we will create a textbox with “readonly” attribute that will populate automatically with the selected option:

<label>Selected Language:</label>
<input type="text" id="textBox" readonly>

Now, in JavaScript file, or a <script> tag, first, we will get the reference of both elements “dropdown” and the “textbox” using their assigned ids with the help of “getElementById()” method:

const dropDown = document.getElementById('dropDown');
const textBox = document.getElementById('textBox');

Call the “addEventListener()” method on the dropdown and use the “change” event that will be fired when the option is selected from the dropdown list. Retrieve the selected value using the “target.value” attribute and set it in the textbox using the “value” attribute:

dropDown.addEventListener('change', (event) => {
 const selectedLanguage = event.target.value;
 textBox.value = selectedLanguage;
});

The output indicates that the selected value from the dropdown has been successfully added in the textbox:

That’s all about the populating textbox based on the dropdown selection in JavaScript.

Conclusion

To populate or fill a textbox based on a dropdown selection, use the drop-down’s “change” event. It will detect the option selected by the user and set them as a textbox’s value. This article described the procedure to fill the textbox depending on the dropdown selection using JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.