I am creating a website and would like to make a tool using JavaScript to choose someone’s skateboard size depending on their shoe size. This is the code I am using:
JavaScript
x
22
22
1
const shoeSize = document.getElementById('shoeSize').value
2
let boardSize = ''
3
switch (shoeSize) {
4
case 0 <= 7:
5
boardSize = '7.75'
6
break;
7
case 8,9:
8
boardSize = '8'
9
break;
10
case 10,11:
11
boardSize = '8.25'
12
break;
13
case 12,13:
14
boardSize = '8.38'
15
break;
16
case 14 >= 20:
17
boardSize = '8.5'
18
break;
19
default:
20
boardSize = '?'
21
document.write(boardSize)
22
}
JavaScript
1
4
1
<p>
2
Most people pick their board size by prefrence but I will make a tool below to choose a board size that will fit your shoe size best. The most popular board sizes are 7.75, 8, 8.25, 8.38, and 8.5. <br> <br>
3
If your shoe size is: <input id='shoeSize' type="text" class="shoe">. The best board size for you would be:
4
</p>
No matter what I type into the text box there is always a “?” that shows up on my website. What can I do/ change to fix this. What I want to happen is if someone types for example “10” into the text box, “8.25” should be printed. I would also appreciate any other tips to improve my code.
Advertisement
Answer
Try this:
JavaScript
1
27
27
1
const shoeSizeInput = document.getElementById('shoeSize')
2
const shoeSizeResult = document.getElementById('resultSize') // Get reference for the element where you want to display result
3
4
// Add event listener which will fire when input is changing
5
shoeSizeInput.addEventListener('input', (event) => {
6
const shoeSize = parseInt(event.target.value) // Get input value and parse to number
7
let boardSize = '?'
8
9
switch (true) {
10
case 0 <= shoeSize && shoeSize <= 7:
11
boardSize = '7.75'
12
break;
13
case shoeSize === 8 || shoeSize === 9:
14
boardSize = '8'
15
break;
16
case shoeSize === 10 || shoeSize === 11:
17
boardSize = '8.25'
18
break;
19
case shoeSize === 12 || shoeSize === 13:
20
boardSize = '8.38'
21
break;
22
case 14 <= shoeSize && shoeSize <= 20:
23
boardSize = '8.5'
24
break;
25
}
26
shoeSizeResult.textContent = boardSize // Set text of result element to board Size
27
})
JavaScript
1
3
1
<p>Most people pick their board size by prefrence but I will make a tool below to choose a board size that will fit your shoe size best. The most popular board sizes are 7.75, 8, 8.25, 8.38, and 8.5.</p>
2
<label>If your shoe size is:</label><input id='shoeSize' type="number" class="shoe">
3
<p id="resultSize"></p>
- Added an event listener. You checked the input value instantly when the page is loading. Therefore it always was empty.
- Changed the switch statement. You can read more about that here: Switch on ranges of integers in JavaScript
- Added a
p
tag to display result. This is better thanwriteDocument()
.