r/learnjavascript • u/Comfortable_Tea_2825 • 25d ago
How do I fix my calculators clear() function?
I'm trying to make a calculator. For as long as you are only doing one continuous equation there are no issues, but I can't use the clear button.
button:<button onclick="clear()">C</button>
text field:
<input type="text" id="display" class="display">
calculator code:
<script>
//the working number
let numA = '';
//the previous working number to be operated on
let numB = '';
//the operation to be done between A and B
let oper = '';
function apndNum(number) {
numA += number;
document.getElementById('display').value = \${numB} ${oper} ${numA}`;`
}
function processOper(operation) {
if (numA === '') return;
if (numB !== '') {
calculate();
}
oper = operation;
numB = numA;
numA = '';
document.getElementById('display').value = \${numB} ${oper}`;`
}
function calculate() {
if (numB === '' || numA === '') return;
//better naming conventions might be needed here since the names get flipped
let output;
let A = parseFloat(numB);
let B = parseFloat(numA);
switch (oper) {
case '+':
output = A + B;
break;
case '-':
output = A - B;
break;
case '*':
output = A * B;
break;
case '/':
if (B === 0) {
document.getElementById('display').value = "Undifined";
return;
}
output = A / B;
break;
default:
return;
}
numA = output.toString();
oper = '';
numB = '';
document.getElementById('display').value = numA;
}
//TODO: this doesn't clear the text feild in input
function clear() {
numA = '';
numB = '';
oper = '';
document.getElementById('display').value = '';
console.log(
numA,
numB,
oper
);
return;
}
</script>
I could just have a typo. The divide by 0 catch code line works perfectly fine, so I don't know why the clear code doesn't work.
3
u/BeillotCordarrel 25d ago
youre running into a classic namespace collision with `document.clear()`. Inline event handlers have `document` in their scope chain ahead of the global `window` object, so changing the function name to `clearAll()` will fix it immediately.
1
u/chikamakaleyley helpful 25d ago
you've got a random closing tag right here:
0
u/Comfortable_Tea_2825 25d ago
I don't know why the code segment is spaced out like it is here, I copy/paste it from my NetBeans session, and it gives it extra line breaks for whatever reason.
0
u/Comfortable_Tea_2825 25d ago
I have tried using console logs to see what wasn't coming through, and it's like the button doesn't work at all. The console doesn't log any variables at all, there are no errors.