Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get value of button with JS

How can I get the value of a button when there are many multiple buttons created? Currently on my Javascript file I have it so my search history makes a button in a list with a "value" of the city that is labeled.

When I click on the button that was made I get undefined.

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following code will log the value of the button to the console when it is clicked.

function recentSearch(city) {
    var addCity = document.createElement("button");
    addCity.setAttribute("value", city);
    addCity.textContent = city;
    addCity.onclick = (e)=>{
        console.log(e.target.getAttribute('value'));
        //or whatever other code you want to do onclick
    }
    document.getElementById("searchHistory").append(addCity);

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading