Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, if the user clicks on "italian" in the dropdown menu, the text input should display "italian".

Although I have written the code, it doesn't seem to be functioning as intended:

<!DOCTYPE html>
<html>
<head>

    <style>
.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}
</style>
</head>
<title>Calculators</title>
<body bgcolor="yellow">
    <h1 style="color:red;">Calculators:</h1><br>

    <p style="margin-left: 50px;">
    <a href="C:\Users\ALBINO\Desktop\prove\calculator\index.html" target="_self">Example Calculator</a><br>
    <a href="index2.html" target="_self">Italian Calculators</a><br>
    <a href="http://web2.0calc.com/">Online Scientific Calculator</a>
    </p>
   
    <div id="examplePicture" style="margin-left: 500px;">
        <img src="http://i.ebayimg.com/00/$T2eC16NHJIkE9qU3jckhBRY0k-ob)!~~_35.JPG" />
    </div>

<div class="dropdown">
  <button onclick="myFunction() class="dropbtn" >Choose your favourite calculator</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#">italian</a>
    <a href="#">german</a>
    <a href="#">brazilian</a>
    <a href="#">french</a>
    <a href="#">spaniard</a>
  </div>
</div>

<input type="text" id="display" disabled><br>

<script src="homeJava.js"></script>

</body>
</html>

Below is the javascript code I've implemented:

var textbox = document.getElementById('display');

function myFunction() {
    textbox.value += document.getElementById("myDropdown").classList.();
}

If anyone could provide some assistance, it would be greatly appreciated.

Answer №1

To implement this feature in your HTML code, make sure to add the following function on change:

<div class="dropdown">
<button class="dropbtn" >Choose your preferred language</button>
<div id="myDropdown" onchange="myFunction()" class="dropdown-content">
  <a href="#">Italian</a>
  <a href="#">German</a>
  <a href="#">Brazilian</a>
  <a href="#">French</a>
  <a href="#">Spanish</a>
 </div>
</div>

Then, in your JavaScript file:

function myFunction{

 $("#myDropdown option:selected").each(function () {
        getSelectedItem = $(this).val();
        $("#display").val(getSelectedItem);
 });
}

Answer №2

Here is a possible solution:

<!DOCTYPE html>
<html>
<head>

    <style>
.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}
</style>
</head>
<title>Calculators</title>
<body bgcolor="yellow">
    <h1 style="color:red;">Calculators:</h1><br>

    <p style="margin-left: 50px;">
    <a href="C:\Users\ALBINO\Desktop\prove\calculator\index.html" target="_self">Example Calculator</a><br>
    <a href="index2.html" target="_self">Italian Calculators</a><br>
    <a href="http://web2.0calc.com/">Online Scientific Calculator</a>
    </p>
    <!--<script src="logic.js"></script> http://www.qatarstationery.com/image/cache/data/Calculator%20MJ100%20-%20Casio-900x900.jpeg-->

    <div id="examplePicture" style="margin-left: 500px;">
        <img src="http://i.ebayimg.com/00/$T2eC16NHJIkE9qU3jckhBRY0k-ob)!~~_35.JPG" />
    </div>

<div class="dropdown">
  <button class="dropbtn" >Choose your favourite calculator</button>
  <div id="myDropdown" class="dropdown-content">
    <a onclick="myFunction('italian')">italian</a>
    <a onclick="myFunction('german')">german</a>
    <a onclick="myFunction('brazilian')">brazilian</a>
    <a onclick="myFunction('french')">french</a>
    <a onclick="myFunction('spaniard')">spaniard</a>
  </div>
</div>

<input type="text" id="display" disabled><br>

<script>
    var box = document.getElementById('display');

    function myFunction(text) {
        box.value = text;
    }
</script>

</body>
</html>

Answer №3

Implement a click listener for all <a> elements that are descendants of the element with the ID #myDropdown

var links = document.getElementById('myDropdown').querySelectorAll('a');
    for (var i = 0; i < links.length; i++) {
      // Add click event listener
      links[i].addEventListener('click', function(){
        // Update input value with the content of the clicked link
        document.getElementById('display').value = this.innerHTML;
      });
    }
<div id="myDropdown" onchange="myFunction()" class="dropdown-content">
  <a href="#">italian</a>
  <a href="#">german</a>
  <a href="#">brazilian</a>
  <a href="#">french</a>
  <a href="#">spaniard</a>
 </div>

<input type="text" id="display" disabled><br>

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

Discover a technique to display every individual "echo" statement from PHP in sequence, rather than waiting for the entire script to finish executing

I have developed a PHP script that takes some time to execute and displays multiple "echo" statements as the progress is being made. The script connects to an FTP server, deletes all contents, and then uploads new files. Everything is functioning correctly ...

What improvements does IE7 offer compared to IE6?

Many developers in the web development industry often express frustration when it comes to developing for IE6. But when working with a powerful JavaScript framework such as jQuery, does the process of developing for IE6 differ significantly from that of ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

Angular: Navigating to another URL causes the page to revert back to the default route

Currently, I am working with Angular 1.3.10, ui-router 0.2.10, and Express 4.14.0 to develop a Reddit-style application, and I'm facing some issues with routing. The simplified version of my Express routes: router.get('/api/home', function ...

How to Align Title in the Center of a Section Containing Multiple Images?

I have a situation where I am using a StyledHead section to display 10 images from an API. The images are wrapped in another section called StyledHeader, which also contains an h1 element. How can I center the h1 element both vertically and horizontally so ...

How can I add a blank selection at the bottom of my ng-options dropdown?

At the moment, my setup looks something like this (in a simplified form): <select ng-model=model.policyHolder ng-options="person.index as person.name for person in model.insurance.persons"> <option value>Someone else </select> This co ...

Connecting MySQL to HTML: Step-by-step guide

I am currently working on building a website through coding in HTML using gedit. My goal is to have a login or registration feature on the homepage, which will then direct users to their own personalized page on the site. On this page, they should be abl ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

Creating a balanced height for child elements using CSS

If you are looking to display a list of colors with each color occupying an equal fraction of the height, here is how you can achieve it. Imagine presenting four colors in a list with a fixed height and a thick border around it: The example shown above is ...

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality. When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages. Upon clickin ...

Using External APIs in React: A Guide

Recently, I created a React app using the npm module 'create-react-app' I ran into an issue where I needed to call an external API from api.example.com, but found that Axios was making requests to localhost instead of the external API. Here is ...

Updating the parent's reference from a child component in Vue 3

In one of my child components, I have a component named Navbar that includes an option for logging out. <a @click="(event) => {event.preventDefault();}"> Logout </a> This Navbar component has been imported into my parent compon ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

What sets apart .create from .save in mongoose?

A while ago, I completed a bootcamp course on Express and Mongoose on Udemy. In the course, we learned how to add new fields to data by writing code like this: var playground = require("../models/playground.js"); route.post("/", middleware.isLoggedIn,fun ...

Unable to bring in Vue component from NPM module

Hello there, I recently developed my own npm package for a navigation bar and I need to incorporate it into my main codebase. Currently, I am utilizing vue @components but I am struggling with integrating the imported component. If anyone has insight on h ...

Displaying geoJSON data from a variable instead of a file is a feature implemented by

Let's say I have a geoJSON data stored in a variable or parsed as an object: // GeoJSON stored as an object var segment = segment; // GeoJSON saved as a JSON string var json = JSON.stringify(segment); Now, the challenge is to display this geoJSON o ...

Struggling with ensuring that Angular-JS pauses and waits for an asynchronous call to complete before moving on

Understanding the use of promises in Angular for handling async operations is crucial, but I'm struggling to implement it effectively in this scenario. function fetchLineGraphData(promises){ var dataPoints = []; for (var i = 0; i < promise ...