Hi I am trying to calculate the percentage using the input from the HTML input
let timeSpend = document.querySelector(".time_spend")
var fSubject = (50/timeSpend)*100;
var sSubject = (25/timeSpend)*100;
var tSubject = (25/timeSpend)*100;
window.alert(fSubject);
This is my HTML input that I have the type of number but I don't know why it still not working
<input
type="number"
id="text-box"
class="time_spend"
placeholder="How much time do you have?"
/>
Here's how you can do it if you want the percentages to be recalculated when you change the value in the input.
I'm outputting the percentages in the html here just as an example
const timeSpendInput = document.querySelector(".time_spend")
const fSubjectSpan = document.querySelector("#fSubject");
const sSubjectSpan = document.querySelector("#sSubject");
const tSubjectSpan = document.querySelector("#tSubject");
timeSpendInput.addEventListener("change", () => {
const timeSpend = timeSpendInput.value;
const fSubject = (50/timeSpend)*100;
const sSubject = (25/timeSpend)*100;
const tSubject = (25/timeSpend)*100;
fSubjectSpan.innerHTML = fSubject;
sSubjectSpan.innerHTML = sSubject;
tSubjectSpan.innerHTML = tSubject;
})
<input
type="number"
id="text-box"
class="time_spend"
placeholder="How much time do you have?"
/>
<br>
<label>fSubject: <span id="fSubject"></span></label>
<br>
<label>sSubject: <span id="sSubject"></span></label>
<br>
<label>tSubject: <span id="tSubject"></span></label>
When you want to get a value out of an input, you should use .value on the element. And when you want do to this should still be decided, do you want it on a submit or a button click. This is an example using a button.
<!DOCTYPE html>
<html lang="en">
<body>
<input type="number" id="text-box" class="time_spend" placeholder="How much time do you have?" />
<button onclick="buttonClicked()">test</button>
</body>
<script>
const buttonClicked = () => {
let timeSpend = document.querySelector(".time_spend").value;
console.log(timeSpend);
var fSubject = (50 / timeSpend) * 100;
var sSubject = (25 / timeSpend) * 100;
var tSubject = (25 / timeSpend) * 100;
window.alert(fSubject);
};
</script>
</html>