'DOM .value attribute not working - returning blank string
For whatever reason, the .value attribute on the input boxes is not returning the values entered. When running it through the Number(), it returns 0, and without it returns a blank string. I have no idea why, I looked at at least a dozen various sites for answers but I can't find an answer. This is really a last-ditch effort to get this thing to work. Thanks in advance, and I hope it's not a dumb syntax thing. Pesky section of code below.
<div>
<label for="angleAInput">A=</label>
<input id="angleAInput" type="number" placeholder="mesure en degrés"><br>
<label for="sideAInput">a=</label>
<input id="sideAInput" type="number" placeholder="mesure en unités de longueur"><br>
<label for="sideBInput">b=</label>
<input id="sideBInput" type="number" placeholder="mesure en unités de longueur">
</div>
<div>
<button class="go">Triangle ou non?</button>
</div>
<h2 class="result"></h2>
<script>
const go = document.querySelector('.go');
const result = document.querySelector('.result');
let A = Number(document.querySelector('#angleAInput').value);
let a = Number(document.querySelector('#sideAInput').value);
let b = Number(document.querySelector('#sideBInput').value);
let bsinA = b * Math.sin(A * Math.PI / 180);
go.addEventListener('click', output);
function output() {
result.textContent = A;
}
</script>
Solution 1:[1]
Those values are the values of the input on page load, not when the user clicks the button.
Retrieve the values inside the click event listener.
<div>
<label for="angleAInput">A=</label>
<input id="angleAInput" type="number" placeholder="mesure en degrés"><br>
<label for="sideAInput">a=</label>
<input id="sideAInput" type="number" placeholder="mesure en unités de longueur"><br>
<label for="sideBInput">b=</label>
<input id="sideBInput" type="number" placeholder="mesure en unités de longueur">
</div>
<div>
<button class="go">Triangle ou non?</button>
</div>
<h2 class="result"></h2>
<script>
const go = document.querySelector('.go');
const result = document.querySelector('.result');
go.addEventListener('click', output);
function output() {
let A = Number(document.querySelector('#angleAInput').value);
let a = Number(document.querySelector('#sideAInput').value);
let b = Number(document.querySelector('#sideBInput').value);
let bsinA = b * Math.sin(A * Math.PI / 180);
result.textContent = A;
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Spectric |
