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:
JavaScript
x
2
1
<button id="kaufknopf" value="4,50">4,50€</button>
2
This is my JS file:
JavaScript
1
7
1
function output() {
2
console.log(price);
3
}
4
5
var price = document.getElementById("kaufknopf").value;
6
price.addEventListener("click", output, true);
7
Advertisement
Answer
1) You have to add event listener on the html element not on the value of that element.
JavaScript
1
3
1
var price = document.getElementById( "kaufknopf" );
2
price.addEventListener( "click", output, true );
3
2) After you click on the button you have to grab its value using price.value
JavaScript
1
4
1
function output() {
2
console.log( price.value );
3
}
4
JavaScript
1
6
1
function output() {
2
console.log(price.value);
3
}
4
5
var price = document.getElementById("kaufknopf");
6
price.addEventListener("click", output, true);
JavaScript
1
1
1
<button id="kaufknopf" value="4,50">4,50€</button>