I written my own calculator script in javascript! It is a basic one, but works really well. I am just wondering if there is any way to make this script more efficient & clean. On first look, I feel like I did some redundant stuff in it, however I am a beginner and in no right to judge the code on my own. Thanks!
Html:
window.onload = () => {
const calculator = document.querySelector('form[name = "calculator"]')
const btns = document.querySelectorAll(`form[name = "calculator"] table tr input[type = "button"]`)
btns.forEach((button) => {
if(button.value != 'c' && button.value != '='){
button.addEventListener('click', () => {
calculator.display.value += button.value
})
} else {
if (button.value == 'c') {
button.addEventListener('click', () => {
calculator.display.value = '';
})
} else if (button.value == '=') {
button.addEventListener('click', () => {
calculator.display.value = eval(calculator.display.value);
})
}
}
})
}
<!DOCTYPE html>
<html>
<head></head>
</body>
<!-- Page Contents !-->
<form name = "calculator">
<table>
<tr>
<input type = "text" name = "display" id = "display" disabled>
</tr>
<tr>
<td><input type = "button" name = "one" value = "1"></td>
<td><input type = "button" name = "two" value = "2"></td>
<td><input type = "button" name = "three" value = "3"></td>
<td><input type = "button" name = "plus" value = "+"></td>
</tr>
<tr>
<td><input type = "button" name = "four" value = "4"></td>
<td><input type = "button" name = "five" value = "5"></td>
<td><input type = "button" name = "six" value = "6"></td>
<td><input type = "button" name = "minus" value = "-"></td>
</tr>
<tr>
<td><input type = "button" name = "seven" value = "7"></td>
<td><input type = "button" name = "eight" value = "8"></td>
<td><input type = "button" name = "nine" value = "9"></td>
<td><input type = "button" name = "multiplicatio" value = "*"></td>
</tr>
<tr>
<td><input type = "button" name = "clear" value = "c"></td>
<td><input type = "button" name = "0" value = "0"></td>
<td><input type = "button" name = "equal" value = "="></td>
<td><input type = "button" name = "division" value = "/"></td>
</tr>
</table>
</form>
<script src = "script.js"></script>
</body>
</html>
JavaScript (The Code That Needs To Be Reviewed):
window.onload = () => {
const calculator = document.querySelector('form[name = "calculator"]')
const btns = document.querySelectorAll(`form[name = "calculator"] table tr input[type = "button"]`)
btns.forEach((button) => {
if(button.value != 'c' && button.value != '='){
button.addEventListener('click', () => {
calculator.display.value += button.value
})
} else {
if (button.value == 'c') {
button.addEventListener('click', () => {
calculator.display.value = '';
})
} else if (button.value == '=') {
button.addEventListener('click', () => {
calculator.display.value = eval(calculator.display.value);
})
}
}
})
}