I've been working on a fun little project to practice my JavaScript skills - a plate calculator.
Here's the gist: you enter your name, and each letter costs $5, so the total cost of the plate is the length of your name multiplied by $5 (this project was inspired by the "Javascript & Jquery" book by Jon Duckett).
But, I've run into a problem that I can't seem to solve. Whenever I click the calculate
button, I get 'Your plate costs NaN dollars'.
I'm convinced I'm missing something obvious, but I just can't figure it out. I thought using .length
was the logical choice.
Another thing, I'm curious why, when I tried setting personName = ''
in the event listener for the refresh button, it didn't work. However, when I used
document.querySelector('.input').value = '';
, it did work. Why couldn't it recognize the variable declared at the beginning?
Here is the JavaScript code snippet:
let personName = document.querySelector('.input').value;
let btn = document.querySelector('.button')
let cost = document.querySelector('.cost')
let yourPlate = document.querySelector('.yourplate')
let refresh = document.querySelector('.refresh')
btn.addEventListener('click', () => {
cost.innerText = personName.lenght * 5;
yourPlate.classList.add('show')
})
refresh.addEventListener('click', ()=> {
document.querySelector('.input').value = '';
yourPlate.classList.remove('show')
})
And here's the HTML code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Plate Cost</title>
</head>
<body>
<div class="body"></div>
<div class="container">
<div class="dot1"></div>
<div class="dot2"></div>
<div class="dot3"></div>
<div class="dot4"></div>
<h1>PLATE CALCULATOR</h1>
<h3>Enter your name and calculate the cost</h3>
<p class="yourplate">Your plate costs <span class="cost"></span> dollars</p>
<div class="calculate">
<input type="text" class="input"><br>
<button type="submit" class="button">Calculate</button>
<button class="refresh">Refresh</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>