0
When ever a user forgets to put a number in an input i want it to set the value for that input to zero to prevent the NaN
i have tried looking it up the only thing i got close was using the if statement along with the alert telling the user the error but i would like it to be more user friendly to make it still execute if a field is empty but that wont work if the any of then come back as a NaN and to make it where a blank field is set to a value of zero here is the code below: https://code.sololearn.com/WD419jEp6C3Q/?ref=app
3 Antworten
+ 9
you can add || 0 to any one of you inputs in JS
for example
var q = parseInt(document.getElementById('qr').value) || 0;
and think about restructuring a bit
for instance make another function that extract a value from HTML element
function getValue(el){
return parseInt(el.value) || 0;
}
var q = getValue(document.getElementById('qr'));
or even just pass the id to the function and use getElementById inside the function
the point is that it would make it easier for you if you break down the code to smaller functions that handles same logic.
+ 6
I guess you can check the input value and verify whether a number or anything at all was there or not, if the input is blank change the value to zero before calling parseInt and process the change output. Good luck!
+ 3
just a small suggestion. in order for the user not to leave the input field empty, you can add the attribute "required" to the input tag. this way the browser will warn you that the left out field has to be filled in order to proceed.