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