I’m trying to create a calculator webapp using JS and I’m running into some problems. I looked at other open threads and tried that code but it didn’t seem to work. I’m currently just trying to log the ID of the button that was pressed, but when I press a button all I get is "undefined" back. Here’s my code:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<p id="text">
<table border="0" id="table">
<tr>
<td><input type="button" id="one" value="1" onClick="calculate();"></td>
<td><input type="button" id="two" value="2" onClick="calculate();"></td>
<td><input type="button" id="three" value="3" onClick="calculate();"></td>
</tr>
<tr>
<td><input type="button" id="four" value="4" onClick="calculate();"></td>
<td><input type="button" id="five" value="5" onClick="calculate();"></td>
<td><input type="button" id="six" value="6" onClick="calculate();"></td>
</tr>
<tr>
<td><input type="button" id="seven" value="7" onClick="calculate();"></td>
<td><input type="button" id="eight" value="8" onClick="calculate();"></td>
<td><input type="button" id="nine" value= "9" onClick="calculate();"></td>
</tr>
<tr>
<td> </td>
<td><input type="button" id="zero" value="0" onClick="calculate();"></td>
</tr>
</table>
<script>
function calculate(){
console.log(this.id);
}
</script>
</body>
</html>
Try like this:
Live demo
Explanation:
window.event holds an information about last occured event. In your case , it’s
'click'event. You can retrieve theDOM Element,which is being clicked, from theeventobject.ThetargetorsrcElementproperty (depends on type of the browser) represents thatDOM Element.