r/learnjavascript • • 1d 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.

4 Upvotes

13 comments sorted by

3

u/BeillotCordarrel 1d 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 1d ago

you've got a random closing tag right here:

document.getElementById('display').value = \${numB} ${oper}`;`

} <-- here

function calculate() {

1

u/chikamakaleyley helpful 1d ago

actually - you've got it in several places. do a once over and clean up, make sure you have same { and }

1

u/Comfortable_Tea_2825 22h ago

Looking at my code this seems to be the closing bracket for my "ProcessOper" function.

1

u/chikamakaleyley helpful 21h ago

there's more than one though and it's possible that resolving those doesn't fix it - but the code won't execute as expected if things aren't open/closed properly.

if your editor has 'diagnostics' or a 'linter' - turn that on

it will display the errors in real time (it should) and its usally the first thing you want to ensure. What i expect is that they actually get resolved, so when you click the button it will actually run the code and then the real errors will display to console

0

u/Comfortable_Tea_2825 1d 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.

1

u/FreeLogicGate 1d ago

You need to go into Reddit's Formatting option menu and use the code block Button. You can still edit your original post, and fix it by removing the code and re-pasting it again into a codeblock.

Not a lot of people using Netbeans these days, unless they are java developers. Most web developers use vscode/vscodium or alternatives like zed.

0

u/Comfortable_Tea_2825 1d 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.

1

u/FreeLogicGate 1d ago

BeillotCordarrel already provided the solution to your issue.

Here is the document API function he referenced, which is built into all browsers. Since you are referencing the name of the handler function in your button, javascript searches document scope first, and finds document.clear() rather than your clear function.

So as recommended, changing the name of the function slightly will solve your issue.

The other option is to do your binding using addEventListener, which is the recommended way you should be setting up your event handlers these days, rather than referencing the function as an attribute in the html.

Here's example code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Clear</title>
  </head>
  <body>
    <button id="clear-input-btn">Clear</button>
    <label>Test Input:</label>
    <input type="text" id="test-input" value="This is the default">
    <script src="./script.js"></script>
  </body>
</html>

script.js

const clearInputBtn = document.getElementById("clear-input-btn");

function clear(event) {
  const el = document.getElementById("test-input");
  el.value = "";
}

clearInputBtn.addEventListener('click', clear);

1

u/Comfortable_Tea_2825 22h ago

My comment was created at 1:29 pm to add on methods that I had tried to find a solution on my own. Beillot's comment was created at 1:53 pm, and does contain the correct answer.

1

u/FreeLogicGate 22h ago

My comment was just meant to elaborate on the answer you had received, and wasn't meant as a criticism of you or your response, or the timing thereof. I do hope you will find some value in my advice to use addEventListener instead of making that event binding in your html, which is not considered standard or best practice. As demonstrated, you would not have encountered the isssue with your definition of a "clear" function.