Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name.

However, after clicking on one of these created buttons, the value returned is undefined.

function recentSearch(city) {
    var newButton = document.createElement("button");
    newButton.setAttribute("value", city);
    newButton.textContent = city;
    document.getElementById("searchHistory").append(newButton);

    cities.push(city);
    localStorage.setItem("searches",JSON.stringify(cities));
}

Answer №1

If you find yourself in a situation where you need to add multiple buttons, it's recommended to utilize event delegation. By attaching a single event listener to the parent container, you can dynamically add buttons and then check in the listener function if the clicked element is a button, logging its value accordingly.

const searchHistory = document.querySelector('#searchHistory');

// Attach a single event listener to the container that invokes `handleClick`
searchHistory.addEventListener('click', handleClick, false);

function handleClick(e) {

  // Extract the nodeName and value from the clicked element
  // If the element is a button, log its value
  const { nodeName, value } = e.target;
  if (nodeName === 'BUTTON') {
    console.log(value);
  }
}

function recentSearch(city) {
  var addCity = document.createElement('button');
  addCity.value = city;
  addCity.textContent = city;
  searchHistory.append(addCity);
}

const cities = ['London', 'Rome', 'New York', 'Seoul', 'Kingston'];

for (const city of cities) {
  recentSearch(city);
}
<div id="searchHistory"></div>

Answer №2

By utilizing the function below, you can capture and display the value of a button on the console whenever it is selected.

function trackCitySelection(city) {
    var selectedCity = document.createElement("button");
    selectedCity.setAttribute("value", city);
    selectedCity.textContent = city;
    selectedCity.onclick = (e)=>{
        console.log(e.target.getAttribute('value'));
        //Add any additional functionality for onclick event here
    }
    document.getElementById("selectedCities").append(selectedCity);

    chosenCities.push(city);
    localStorage.setItem("chosenCitiesList",JSON.stringify(chosenCities));
}

Answer №3

Utilize data-attributes for more streamlined code readability and an efficient way to transmit data within elements. Access the data with ease using

element.dataset.<attribute_name>
, like with e.target.dataset.value when triggering a button click event listener.

cities = []

function recentSearch(city) {
  // FOR DEMO ONLY::
  if (!city) city = "city " + Math.ceil(Math.random() * 1000);

  var addCity = document.createElement("button");
  addCity.setAttribute("data-value", city);
  addCity.textContent = city;
  addCity.addEventListener('click', e => {
    console.log(`my city is: ${e.target.dataset.value}`);
  })
  document.getElementById("searchHistory").append(addCity);
  

  cities.push(city);
  // localStorage.setItem("searches",JSON.stringify(cities));
}
<div id='searchHistory'>
</div>
<button onclick='recentSearch()'>Make City</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

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

What is the best way to run a code block every time a new reaction is added in discord.js?

I need assistance with creating a bot that can count the number of specific reactions ('⚪') to a message within a specified time frame. Additionally, I want to be able to skip the remaining time by reacting to a different emoji ('X'). ...

Buefy table in Vue with various row statuses

One interesting feature of Buefy tables is the ability to highlight rows with a specific color based on a variable in the row. :row-class="(row, index) => row.variable === x && 'is-info'"> In order to style the specific row class: <styl ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

How can I use AJAX to update a DIV when an image is swapped out?

I run an online radio station and I've been looking for a way to display album artwork for each song that plays. After setting up the ability to automatically upload the image of the currently playing song as "artwork.png" to a web server via FTP, I c ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

I'm having trouble with my React Router Dom Redirect path. Everything seems to be set up correctly, but for some reason, it's not directing my home page

I have been working on adding a private route to my main dashboard, which is my home page, to make it accessible only to authenticated users. I created a new component called PrivateRoute and set up the redirection to the login page if the user is not auth ...

Node.js server experiencing delays due to V8 processing constraints

REVISED I am currently running a nodeJS http server designed to handle uploads from multiple clients and process them separately. However, I have encountered an issue where the first request seems to block any subsequent requests until the first one is co ...

Issue with AJAX and JavaScript persisting upon second attempt

My website uses jQuery to load the app page into a div on the index page. The app page consists of two DIVs: a search form and a results div. When the user searches, jQuery loads the results into the results div. Each result includes call-to-action butto ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Is there a way to implement jQuery.closest() using DOM manipulation or pure JavaScript?

Here is the HTML I am attempting to target. Given this HTML structure: <table class="non-unique-identifier table"> <tr><td><div id="unique-identifier"></div></td></tr> </table> I am trying to select #unique ...

Using AngularJS to auto-populate additional fields after selecting an option from the typeahead autocomplete feature

Just starting with AngularJS and finally figured out how to implement Auto-complete in Angularjs. Now, when a user selects a value from the auto-complete, I want other fields to be populated based on that selection. For example, upon loading the screen, d ...

Using React.JS: Display Object Map in rendering

I have an object with family information that looks like this: Family: Parent0: BirthPlace: "dsa" Birthday: "2021-01-04" Relationship: "dsa" SurnameAndName: "dasdsa" Parent1: BirthPlace: & ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

Angular ng-if directive contains a specific class

I am trying to create a directive that will only be active when an element has a specific class. I have tried the following code: <feedback-analytics ng-if="$('#analyticTab').hasClass('active')"></feedback-analytics> Unfor ...

Limit the API call to only respond to requests from the localhost

I'm currently working on a website that uses API calls within the same node project. I would like to restrict most of these API calls to only be accessible by the localhost website. Is there a way to achieve this without implementing OAuth and simply ...

Chrome and Firefox: Images cling together

I've encountered an issue with my recently launched website. Some images in a grid appear to be stuck together, but this problem only occurs in Firefox and Chrome browsers. Oddly enough, zooming in to around 110% then back to 100% seems to temporarily ...

Resetting JavaScript Input based on certain conditions

I have been attempting to reset the input fields for a login when the loginDiv display is set to none, but unfortunately it does not seem to be working as expected. My goal is for the input fields to reset whenever the login button is clicked and the logi ...

VUEJS - Link the output from my function to my sub-template

I am looking for a way to link the output of my function with the child template. methods object methods: { filterOptions(checkedValues: any) { let filtered = this.cards.filter(card => { return card.profile .map(prof ...