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

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

When styled with an id, the DIV element does not inherit styles from a CSS class

I seem to be facing an issue with the code below, possibly due to using both class and id in the same div. Despite knowing they are meant to work together. For more information: Can I use DIV class and ID together in CSS? .PB { position: relative; ...

Using Node.js and MongoDB to filter a sub array within an array of objects

Hello everyone, I currently have an array of objects containing some populated fields. Below is the product schema: import mongoose, { Schema } from 'mongoose'; const productSchema = new mongoose.Schema( { name: String, description: S ...

From HTML element to pug-template with the use of the # symbol

I have a code snippet with 2 angular material radio buttons. Both of them contain the #attribute/element (I'm not sure what it's called) within them. How can I convert them into pug so that the attribute/element with the # works? Below is the sam ...

Tips for retrieving the xpath of elements within a div using python selenium

<div class="col-md-6 profile-card_col"> <span class="label">Company Name :</span> <p class="value">Aspad Foolad Asia</p> </div> For a while now, I've been trying to troublesho ...

The only thing visible on my project is the homepage, void of any buttons or additional pages

After completing this school project, I believed that everything was done correctly. However, as I faced issues with the code, I decided to seek help and share my app.js and bin section for clarification. Starting it with npm on the localhost as shown in ...

Implementing a smooth transition for a never-ending CSS rotation animation upon clicking a different div with the help of jQuery

I am attempting to utilize jquery in order to bring a constantly rotating div (with CSS animation) to a gradual, smooth halt when another div is clicked. My current strategy involves changing the "animation-timing-function" property from "linear" to "ease ...

JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this: array = [ { "name": "name", "value": "Olá" }, { "name": "age" ...

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

Issue with displaying a vTable component in VueJS / Vuetify

I am struggling with this basic HTML/Vue/Vuetify code snippet below, and I can't seem to get it functioning as intended. const { createApp, computed, ref, reactive } = Vue; const { createVuetify } = Vuetify; const ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

The request has been unsuccessful with error code 405 in Nextjs version 14

I am currently working with NextJs version 14 and encountering a 405 error: GET http://localhost:3000/api/products 405 (Method Not Allowed) Uncaught (in promise) AxiosError products.js "use client" import { useState } from 'react'; ...

Background Services in the Moment

Currently in the process of developing a mobile application with the Ionic framework that utilizes Laravel 4 REST API for CRUD operations on a MySQL database. As per the requirements of the app, it needs to constantly communicate with the backend service t ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

Sending files through ajax with php

Hey there! I've been working on uploading files using Ajax and PHP, following a tutorial. Here's the code I have so far: upload.js: var handleUpload = function (event){ event.preventDefault(); event.stopPropagation(); var fileInput= document.ge ...

Running Selenium tests are not able to initiate Javascript ajax requests

I'm currently troubleshooting a scenario using Selenium that involves the following steps: - When a user inputs text into a textarea, an ajax request is sent, which then adds the text to the database (implemented using django and processed in view.py) ...

Is there a way to ensure that my text is centered on top of an image while maintaining responsiveness?

I'm trying to make the text adjust its center to the height of an image that changes size when the page is resized. Here's what I have so far: HTML <section id="eyeCatcher"> <div id="catchContainer" > <div id="eyeCatchQ ...