CodingNic

Number Input & Display Logic

Connect Number Input to the Display

Number Input & Display Logic 25 min read

Connect Number Input to the Display

Task

Connect the calculator’s number input methods to the prepared buttons and display.

Open

Open:

js/ui.js

Use the calculator instance created in calculator.js, then listen for clicks on the prepared number and decimal buttons.

If your starter markup uses different selectors, keep the existing selectors from the starter and change only the JavaScript event wiring.

Add the event handling

The exact selectors depend on the prepared starter markup. For a starter using data-action attributes, the logic can be:

javascript
const buttons = document.querySelectorAll('[data-action]');

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    const action = button.dataset.action;

    if (action === 'digit') {
      calculator.inputDigit(button.dataset.value);
    }

    if (action === 'decimal') {
      calculator.inputDecimal();
    }

    updateDisplay();
  });
});

Then create the display update function using the display element already provided by the starter:

javascript
function updateDisplay() {
  display.textContent = calculator.state.current;
}

Call it once when the application starts:

javascript
updateDisplay();

If the starter already provides buttons, display, or an event-handler structure, add the same logic to those existing variables rather than duplicating them.

Test

In the browser:

  1. Click 7.
  2. Click 5.
  3. Click ..
  4. Click 2.

The display should show:

text
75.2

Then refresh the page. The initial display should return to 0.

Check the console for errors.

Checkpoint

Number and decimal buttons now travel through the application logic and update the visible calculator display.