Problem using parseFloat even though I am parsing a number, but still returing NaN
<div class="tip-custom" id="tip-custom"><input type="number" placeholder="CUSTOM"></div>
const tipCustom = document.querySelector(".tip-custom");
tipCustom.addEventListener("input", tipInputFun);
let tipValue = 0.15;
function tipInputFun() {
tipValue = parseFloat(tipCustom.value / 100);
console.log(tipValue);
}
CodePudding user response:
Your querySelector
looks for an element that has a class tip-custom
.
In your code I see a div
with id tip-custom (that is #tip-custom
) and your input being inside the div.
You need to fix your selector to properly find the element with your text. You could do something like this
document.querySelector("#tip-custom>input");
Takes the first input, inside an element with id tip-custom.
const tipCustom = document.querySelector("#tip-custom>input");
tipCustom.addEventListener("input", tipInputFun);
let tipValue = 0.15;
function tipInputFun() {
tipValue = parseFloat(tipCustom.value / 100);
console.log(tipValue);
}
<div class="tip-custom" id="tip-custom"><input type="number" placeholder="CUSTOM"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
tipCustom
is the div, not the input, so tipCustom.value
is undefined.
CodePudding user response:
Keep it simple and follow the good practices.
let tipValue = 0.15;
function tipInput() {
tipValue = parseFloat(this.value / 100);
console.log(tipValue);
}
document.querySelector(".tip-custom > input").addEventListener("input", tipInput);
<div class="tip-custom" id="tip-custom"><input type="number" placeholder="CUSTOM"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>