-2

I am working on a calculator project but I should get in it keyboard support I tried to do that but my calculator crashed and it isn't working can you help

I used this website https://www.section.io/engineering-education/building-a-calculator-a-javascript-project-for-beginners/ to do my calculator There aren't any errors in the console and when I click on any button nothing shows up

js code

    class Calculator {
    constructor(previousOperandTextElement, currentOperandTextElement) {
    this.previousOperandTextElement = previousOperandTextElement
    this.currentOperandTextElement = currentOperandTextElement
    this.clear()
    }

    clear() {
    this.currentOperand = ''
    this.previousOperand = ''
    this.operation = undefined
    }

    delete() {
        this.currentOperand = this.currentOperand.toString().slice(0, -1)
    }

    appendNumber(number) {
        this.currentOperand = this.currentOperand.toString() + number.toString()
    }

    chooseOperation(operation) {
        if (this.currentOperand === '') return
        if (this.previousOperand !== '') {
            this.compute()
        }
        this.operation = operation
        this.previousOperand = this.currentOperand
        this.currentOperand = ''
    }

    compute() {
    let computation
    const prev = parseFloat(this.previousOperand)
    const current = parseFloat(this.currentOperand)
    if (isNaN(prev) || isNaN(current)) return
    switch (this.operation) {
        case '+':
        computation = prev + current
        break
        case '-':
        computation = prev - current
        break
        case '×':
        computation = prev * current
        break
        case '÷':
        computation = prev / current
        break
        default:
        return
    }
    this.currentOperand = computation
    this.operation = undefined
    this.previousOperand = ''
    }

    getDisplayNumber(number) {
    const stringNumber = number.toString()
    const integerDigits = parseFloat(stringNumber.split('.')[0])
    const decimalDigits = stringNumber.split('.')[1]
    let integerDisplay
    if (isNaN(integerDigits)) {
        integerDisplay = ''
    } else {
        integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })
    }
    if (decimalDigits != null) {
        return `${integerDisplay}.${decimalDigits}`
    } else {
        return integerDisplay
    }
    }

    updateDisplay() {
    this.currentOperandTextElement.innerText =
        this.getDisplayNumber(this.currentOperand)
    if (this.operation != null) {
        this.previousOperandTextElement.innerText =
        `${this.getDisplayNumber(this.previousOperand)} ${this.operation}`
    } else {
        this.previousOperandTextElement.innerText = ''
    }
    }
}


const numberButtons = document.querySelectorAll('[data-input]')
const operationButtons = document.querySelectorAll('[data-symbol]')
const equalsButton = document.querySelector('[data-equels]')
const deleteButton = document.querySelector('[data-del]')
const allClearButton = document.querySelector('[data-ac]')
const previousOperandTextElement = document.querySelector('[data-previous-operand]')
const currentOperandTextElement = document.querySelector('[data-current-operand]')

const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement)


numberButtons.forEach(button => {
    button.addEventListener('click', () => {
    calculator.appendNumber(button.innerText)
    calculator.updateDisplay()
    })
})

operationButtons.forEach(button => {
    button.addEventListener('click', () => {
    calculator.chooseOperation(button.innerText)
    calculator.updateDisplay()
    })
})

equalsButton.addEventListener('click', button => {
    calculator.compute()
    calculator.updateDisplay()
})

allClearButton.addEventListener('click', button => {
    calculator.clear()
    calculator.updateDisplay()
})

deleteButton.addEventListener('click', button => {
    calculator.delete()
    calculator.updateDisplay()
})


function keyboardInput(key) {
    if ((key.which < 0 || key.which > 57) && (key.which !== 13 && key.which !== 99)) {
        return false;
    } else {
        key.preventDefault();
        if (key.which === 48) {
            currentOperandTextElement.value += "0";
        } else if (key.which === 49) {
            currentOperandTextElement.value += "1";
        } else if (key.which === 50) {
            currentOperandTextElement.value += "2";
        } else if (key.which === 51) {
            currentOperandTextElement.value += "3";
        } else if (key.which === 52) {
            currentOperandTextElement.value += "4";
        } else if (key.which === 53) {
            currentOperandTextElement.value += "5";
        } else if (key.which === 54) {
            currentOperandTextElement.value += "6";
        } else if (key.which === 55) {
            currentOperandTextElement.value += "7";
        } else if (key.which === 56) {
            currentOperandTextElement.value += "8";
        } else if (key.which === 57) {
            currentOperandTextElement.value += "9";
        } else if (key.which === 46) {
            currentOperandTextElement.value += ".";
        } else if (key.which === 40) {
            currentOperandTextElement.value += "(";
        } else if (key.which === 41) {
            currentOperandTextElement.value += ")";
        } else if (key.which === 42) {
            currentOperandTextElement.value += "*";
        } else if (key.which === 47) {
            currentOperandTextElement.value += "/";
        } else if (key.which === 43) {
            currentOperandTextElement.value += "+";
        } else if (key.which === 45) {
            currentOperandTextElement.value += "-";
        } else if (key.which === 13) {
            calculator.compute()
            calculator.updateDisplay()
        } else if (key.which === 99) {
            calculator.clear()
            calculator.updateDisplay()
        } else {
            currentOperandTextElement.value = display.value;
        }
        return true;
    }
}

function backspaceKeyEvent (event) {
    if (event.which === 8) {
        calculator.delete()
    }
}

    document.onkeypress = keyboardInput;
    document.onkeydown = backspaceKeyEvent;

Html code

    <main class="clac__body">
  <section class="clac__body-screen" id="screen">
    <div class="previous-operand" data-previous-operand></div>
    <div class="current-operand" data-current-operand></div>
  </section>
  <section class="clac__body">
    <div class="calc__body-btn">
      <input class="btn del-btn" type="button" data-input value="(">
      <input class="btn del-btn" type="button" data-input value=")">
      <input class="btn del-btn" type="button" data-del value="DEL">
      <input class="btn reset-btn" type="button" data-ac value="AC">
      <input class="btn nums-btn" type="button" data-input value="7">
      <input class="btn nums-btn" type="button" data-input value="8">
      <input class="btn nums-btn" type="button" data-input value="9">
      <input class="btn symbol-btn" type="button" data-symbol value="÷">
      <input class="btn nums-btn" type="button" data-input value="4">
      <input class="btn nums-btn" type="button" data-input value="5">
      <input class="btn nums-btn" type="button" data-input value="6">
      <input class="btn symbol-btn" type="button" data-symbol value="×">
      <input class="btn nums-btn" type="button" data-input value="1">
      <input class="btn nums-btn" type="button" data-input value="2">
      <input class="btn nums-btn" type="button" data-input value="3">
      <input class="btn symbol-btn" type="button" data-symbol value="-">
      <input class="btn nums-btn" type="button" data-input value=".">
      <input class="btn nums-btn" type="button" data-input value="0">
      <input class="btn equel-btn symbol-btn" data-equels type="button" value="=">
      <input class="btn symbol-btn" type="button" data-symbol value="+">
    </div>
  </section>
</main>
wajd
  • 25
  • 1
  • 7

1 Answers1

1

In the case below button.innerHTML returns null because your <input> tag has no innerHTML (example below). In order to access the value attribute of the input button object just use button.value

    numberButtons.forEach(button => {
      button.addEventListener('click', () => {
        calculator.appendNumber( button.value );
        calculator.updateDisplay();
      })
    })
<!-- No inner html, input tag with a self-closure -->
<input class="btn nums-btn" type="button" data-input value="3" />

<!-- Here is an example with innerHTML, where the tag is closed with its own </input>, this is incorrect html... just an example -->
<input class="btn nums-btn" type="button" data-input value="3">3</input>

I see a lot of the same type of error several times throughout. Hope this helps.

Lucretius
  • 1,053
  • 1
  • 13
  • 26
  • 1
    `button.innerHTML`does not exists here, because an input field has no inner html. Better `button.value`. – Reporter Jun 14 '22 at 13:56
  • Firstly thank you for helping me. I changed the input element inside HTML to be a button element and everything worked again, but for the keyboardInput() function isn't working do you have any idea? – wajd Jun 14 '22 at 14:02
  • https://stackoverflow.com/questions/4416505/how-to-take-keyboard-input-in-javascript The line `document.onkeypress = keyboardInput;` will have to be rewritten to correctly bind to the `keydown` event. – Lucretius Jun 14 '22 at 14:06