I’m fairly new to HTML and JS. I need the value of my HTML button to show in the console.log with JS. I dont want to use onclick=”…” though.
This is part of my HTML file:
<button id="kaufknopf" value="4,50">4,50€</button>
This is my JS file:
function output() { console.log(price); } var price = document.getElementById("kaufknopf").value; price.addEventListener("click", output, true);
Advertisement
Answer
1) You have to add event listener on the html element not on the value of that element.
var price = document.getElementById( "kaufknopf" ); price.addEventListener( "click", output, true );
2) After you click on the button you have to grab its value using price.value
function output() { console.log( price.value ); }
function output() { console.log(price.value); } var price = document.getElementById("kaufknopf"); price.addEventListener("click", output, true);
<button id="kaufknopf" value="4,50">4,50€</button>