What is the best way to choose dropdown values by utilizing various button IDs?

I have four different vacation destinations and four buttons. I want to automatically select each destination separately when the corresponding button is clicked.

<select class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f1990" placeholder="" data-required="true">
    <option value="897">Athens - 5 days / 4 nights - Total Tax: $132.44</option>
    <option value="896">Atlanta - 4 days / 3 nights - Total Tax: $99.75</option>
    <option value="895">Atlantic City - 4 days / 3 nights - Total Tax: $89.10</option>
    <option value="894">Bali - 8 days / 7 nights - Total Tax: $196.84</option>
</select>




<button id="1"> Redeem Athens </button>
<button id="2"> Redeem Atlanta </button>
<button id="3"> Redeem Atlantic City </button>
<button id="4"> Redeem Bali </button>

Answer №1

A clever solution has been found for the issue at hand

const select = document.querySelector('.aa')
const buttons = document.querySelectorAll('button')

buttons.forEach(button => button.addEventListener('click', handler))

let mapOptions = { "1": "897", "2": "896", "3": "895", "4": "894" }

function handler(ev) {
  select.value = mapOptions[ev.target.id]
}
<select class="aa" required="" name="f1990" data-multiple="" data-size="" id="f1990" placeholder="" data-required="true">
    <option value="897">Athens - 5 days / 4 nights - Total Tax: $132.44</option>
    <option value="896">Atlanta - 4 days / 3 nights - Total Tax: $99.75</option>
    <option value="895">Atlantic City - 4 days / 3 nights - Total Tax: $89.10</option>
    <option value="894">Bali - 8 days / 7 nights - Total Tax: $196.84</option>
</select>




<button id="1"> Redeem </button>
<button id="2"> Redeem </button>
<button id="3"> Redeem </button>
<button id="4"> Redeem </button>

Answer №2

Utilize the value attribute to assign values to options and buttons.

let cities = document.getElementById("f1990")
        document.querySelectorAll("button").forEach(b => b.addEventListener("click", function setRedeem(e) {
            cities.value = e.target.value
        }, false))
<select class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f1990" placeholder=""
        data-required="true">
        <option value="897">Athens - 5 days / 4 nights - Total Tax: $132.44</option>
        <option value="896">Atlanta - 4 days / 3 nights - Total Tax: $99.75</option>
        <option value="895">Atlantic City - 4 days / 3 nights - Total Tax: $89.10</option>
        <option value="894">Bali - 8 days / 7 nights - Total Tax: $196.84</option>
    </select>

    <button id="1" value="897"> Redeem </button>
    <button id="2" value="896"> Redeem </button>
    <button id="3" value="895"> Redeem </button>
    <button id="4" value="894"> Redeem </button>

Answer №3

To achieve this, you can utilize the selectedIndex property if the buttons' index corresponds to the options' index (refer to option 1 - selectOptionByIndex).

Alternatively, assign value attributes to the buttons that match the values of the options (option 2 - selectOptionByValue).

Check out the live demonstration: https://stackblitz.com/edit/typescript-r4vuzj

document.querySelectorAll('button').forEach((item, index) => {
  item.addEventListener('click', event => {
    var value = item.getAttribute("value");
    selectOptionByIndex(index);  // option 1
    selectOptionByValue(value);  // option 2
  })
})

function selectOptionByIndex(index) {
  var select = (document.getElementById('mySelect')) as HTMLSelectElement;
  select.selectedIndex = index;
}

function selectOptionByValue(value) {
  var select = (document.getElementById('mySelect')) as HTMLSelectElement;
  select.value = value;
}

If you opt for the second approach - selecting by value - ensure to include the same value attribute in the buttons like so:

<select id="mySelect" class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f1990" placeholder="" data-required="true">
    <option value="897"& gt;Athens - 5 days / 4 nights - Total Tax: $132.44</option>
    <option value="896">Atlanta - 4 days / 3 nights - Total Tax: $99.75</option>
    <option value="895">Atlantic City - 4 days / 3 nights - Total Tax: $89.10</option>
    <option value="894">Bali - 8 days / 7 nights - Total Tax: $196.84</option>
</select>

<br>

<button id="1" value="897" name="btn"> Redeem </button>
<button id="2" value="896" name="btn"> Redeem </button>
<button id="3" value="895" name="btn"> Redeem </button>
<button id="4" value="894" name="btn"> Redeem </button>

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

"Patience is key when it comes to waiting for components to render

Short Overview of the Issue I'm currently exploring methods to access an onRendered lifecycle hook. Finding on the Topic A similar query was posted here: Vue $nextTick in mounted() hook doesn't work as expected The explanation provided suggests ...

Is there a way to manipulate CSS to update automatically when new content is loaded via ajax?

I need help with customizing the CSS for 4 image links on my website. Each link is represented by a small image in its normal state and a larger image when hovered over. The content for each link is loaded using ajax. My question is how can I modify the C ...

What is the best way to define relative paths for content like CSS files?

Whenever I link to a file, I always find myself having to include the entire absolute path like this <link rel="stylesheet" type="text/css" href="F:/XmppOld/XAMPP2/htdocs/MAIN_SITE_LAYOUT/css/stylemainpage.css" /> I want to simplify it to ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...

There is an unnecessary gap between the parent div and the image contained within it

Snippet of HTML code showcased below: <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="css/style.css" rel="style ...

Is it better to store JSON data locally using cookies or HTML5 local storage?

Currently, I am working on developing a mobile website using jquery mobile. My main concern right now is how to efficiently carry JSON data across multiple pages. I am debating whether it would be better to store this JSON data in a cookie or use HTML5 loc ...

The Ajax call was successful but the callback function failed to return

I've been encountering some challenges with a small application I'm developing. After successfully setting it up to automatically populate one field with the same value entered in another field, I decided to integrate an AJAX request into the scr ...

Timeout of 30 seconds added to Axios network requests in Javascript

self.$axios .$get( `https://verifiedpro.herokuapp.com/getvmsstate?kiosk=${self.kiosk}` ) .catch(error => { console.log(error); location.reload(); }) .then(response => { console.log(respons ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

search a database field by querying HTML form input

Looking for assistance with creating a query to input a code in an HTML form, search it against a database field, and display the corresponding database fields on a new page. I have already set up the database and established a working PHP script to connec ...

Navigating horizontally with buttons in VueJS

I am searching for a way to implement horizontal scrolling using buttons in VueJS. The idea is to have a container with multiple divs arranged horizontally, and I wish to navigate through them using the buttons. If you want to see a similar solution using ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Guide on sending files through an API request with formData() using Vuejs and Axios

My goal is to utilize an API to upload a file to the server. The documentation on documenter.getpostman outlines how to use the API: --form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/U ...

Data structures of advanced complexity within HTML data attributes

I am delighted by the existence of the html5 data attribute. It's great to be able to input a plain string into html attributes and retrieve them using jquery. However, wouldn't it be wonderful to have more than just a basic string? Is there a ...

Having trouble grasping the display property combination in Bootstrap4

Incorporating Bootstrap4 into my web application, I am faced with the task of displaying a menu exclusively on the large screen size setting (lg). The guidelines are straightforward: utilize a class to conceal an element across all screen sizes: .d-none ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

Guide on how to reload the page with its initial URL after the URL has been modified using history.pushState()

After utilizing history.pushState(), I encountered an issue where the page would refresh with the current URL instead of the original one when the user refreshed the page. I attempted to detect a page refresh using methods such as cookies and hidden field ...

Having trouble with understanding the usage of "this" in nodejs/js when using it after a callback function within setTimeout

It's quite peculiar. Here is the code snippet that I am having trouble with: var client = { init: function () { this.connect(); return this; }, connect: function () { var clientObj = this; this.socket = ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

Submitting a nested JSON body in ASP MVC

I'm currently struggling to send a nested JSON body to an API, and I've tried a few different approaches without success. The JSON values are sourced from multiple models, making it quite complex for me to handle. Any assistance or guidance on th ...