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

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

Froala text area is unexpectedly visible when I attempt to cover it with a partially see-through mask

The website I'm currently developing features a semi-transparent overlay that dims the screen with a light-colored message displayed on top. This overlay and message are shown whenever there is a background process running. Everything was running smoo ...

Control the access to shared resources when dealing with asynchronous functions in JavaScript

Currently, I am developing a node.js server script that will utilize a shared text list for multiple clients to access asynchronously. Clients have the ability to read, add, or update items within this shared list. static getItems(){ if (list == undef ...

Tips for preventing the unwanted portrayal of a rectangle on canvas?

As a beginner in javascript, I am currently learning about the canvas. I have a question regarding drawing rectangles from right to left and seeing negative numbers in the inputs. Is there a way to display the real size of the rectangle regardless of the d ...

What is the method for inserting data into an array of objects in JavaScript?

I have a question regarding how to push/replace data into an object of an array of objects. Please excuse any mistakes in my grammar. Here is my dummy data: const dummyData = { id: 1, daerah: "Bandung", date:"1668790800000& ...

Disallowing selection on input text field

I am seeking to disable selection on an input field while still allowing for focusing, with the following criteria: Preventing selection via mouse Preventing selection via keyboard (including Ctrl+A, shift+arrows) Permitting focus on the field using both ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

What could be causing the React-Router-Dom Outlet to not show the component?

I am working on a component that houses four different components. const ProtectedRoute = () => { return ( <> <Header /> <div className='flex h-screen overflow-hidden'> <div className="md:block h ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

The Rails/Ajax function is not replacing the DIV as expected, but rather nesting a new DIV inside

Struggling to dynamically update a DIV using AJAX after a form submission. Here is the content of my partial _inline.html.erb: <div class="large-12 columns" id="inline_posts"> <% @posts.each do |post| %> <div class="row"> <div ...

How can you utilize jQuery to iterate through nested JSON and retrieve a specific matching index?

In the scenario where I have a nested JSON object like this: var library = { "Gold Rush": { "slides": ["Slide 1 Text","Slide 2 Text","Slide 3 Text","Slide 4 Text"], "bgs":["<img src='1.jpg' />","","<img src='2.j ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Discover the concealed_elem annotations through the power of JavaScript

As I work on my new website, I am struggling with narrowing down the web code. I came across a solution that seems fitting for what I need, but unfortunately, I can't seem to make it work: I attempted the non-jQuery solution, however, I must be missi ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Looking to utilize vue.js to alter the color of the <li> element when a select option is chosen

I'm a beginner in vue.js and I'm attempting to change the background color by using the select option. Despite trying the cueCardsColor method, nothing seems to be happening. <ul> <li :class="+ cueCardColor"> <sele ...

Creating dynamic Ionic slides by fetching data from a database

I am currently experimenting with Ionic. Web development is not my strong suit, so I may be a bit off the mark. However, I would like to retrieve data from an SQLite database and display it on an ion-slide-box. Here is what I have attempted: function sel ...

Positioning a Material UI Menu item underneath its parent element using CSS styling

I have created a Material UI dialog that features some text and an Icon with a dropdown menu option. You can check out the demo here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js My goal is to properly position the Menu component so that it a ...