I am creating a calculator using HTML, CSS and JavaScript. I would like each number button to return the value of the HTML button clicked as an alert for now, to do this I am trying to use a singular JavaScript function to only return the value of the button which called it.
HTML Code:
<button id="btn" type="button" value="1" onclick="display_num()"><b>1</b></button>
<button id="btn" type="button" value="2" onclick="display_num()"><b>2</b></button>
<button id="btn" type="button" value="3" onclick="display_num()"><b>3</b></button>
JavaScript Code:
function display_num() {
var num = document.getElementById("btn").value
alert(num)
Any help would be greatly appreciated and I apologise in advance if the HTML is a bit of a mess.
CodePudding user response:
Pass a reference
function display_num(btn) {
var num = btn.value
console.log(num)
}
<button id="btn" type="button" value="1" onclick="display_num(this)"><b>1</b></button>
<button id="btn" type="button" value="2" onclick="display_num(this)"><b>2</b></button>
<button id="btn" type="button" value="3" onclick="display_num(this)"><b>3</b></button>
Better answer is to use event delegation
function display_num(evt) {
const btn = evt.target.closest("button");
if (!btn) return
var num = btn.value
console.log(num)
}
document.getElementById("wrapper").addEventListener("click", display_num);
<div id="wrapper">
<button id="btn" type="button" value="1"><b>1</b></button>
<button id="btn" type="button" value="2"><b>2</b></button>
<button id="btn" type="button" value="3"><b>3</b></button>
</div>
CodePudding user response:
Try this html code :
<button id="btn" type="button" value="1" onclick="display_num(1)"><b>1</b></button>
<button id="btn" type="button" value="2" onclick="display_num(2)"><b>2</b></button>
<button id="btn" type="button" value="3" onclick="display_num(3)"><b>3</b></button>
JavaScript code :
function display_num(num) {
alert(num)
}
CodePudding user response:
Event handlers should be passed an event parameter from which you can grab the information you need.
function display_num(e) {
var num = e.currentTarget.value
alert(num)
}
<button id="btn" type="button" value="1" onclick="display_num(event)"><b>1</b></button>
<button id="btn" type="button" value="2" onclick="display_num(event)"><b>2</b></button>
<button id="btn" type="button" value="3" onclick="display_num(event)"><b>3</b></button>