@elaineleung
Posted
Hi Ash, about the validation, I was able to use CSS to check whether it's working, and sure enough the element is able to validate the input value, so at least on the HTML side, things should be OK, except I couldn't get the message to show up since it's on the JS side, which brings me to this:
Regarding the invalid message, try using if (inpeopleCount.value < 1 || inpeopleCount.value == "")
instead, because inpeopleCount
is a DOM element object and is not a number, which is why using inpeopleCount < 1
would always evaluate to false. What you want to do is to get the value in the inpeopleCount
object. If that doesn't work, then I'd suggest that you add event
in the function and then use event.data
for the validation (which is what I did).
Good luck! 🙂
@DavidMorgade
Posted
@elaineleung Hello Elaine, great explanation in this case you are completely correct, inpeopleCount will always return false when comparing to a number because its a DOM element.
In this time is not the case but be carefull when comparing direct values from DOM elements with numbers, cause they return strings, in this case inpeopleCount.value
returns '1' not 1, when comparing strings to numbers in Javascript it will convert the string to a number before the comparation unless you are using the strict equality operator ===
(wich should be use in 99% of the cases!). I would recommend, always, and even if its not necesary, to convert your DOM 'number' (they are not numbers they are strings!) to a number before using it on your function / condition / anything to avoid getting future bugs.
And to recap, as Elaine set, using the event
is a better option in this case!
@elaineleung
Posted
@DavidMorgade Hi David, thanks for your insight, as always. I think because the input here is a number input, the input text is already converted to a number, and so I was able to type in a number and have it evaluate to true in the conditional without converting it myself.
@DavidMorgade
Posted
@elaineleung You can try it on the console typeof inpeopleCount.value
, it returns a string even when the number is an input of type number! You don't need to convert it because Javascript does it for you, unless you use the ===
strict operator.
@elaineleung
Posted
@DavidMorgade Yes, actually just console logging the element itself it can be seen that the value
is clearly a string. I just thought all this time that when MDN says the number input has validation to reject nonnumerical entries, maybe there's some magic that's turning the string values into numbers, and it didn't occur to me that it's JS doing its work with string/number comparison. In any case, I cloned Ash's repo for troubleshooting, and it turns out that the problem in the code was just a curly brace. 😂 Anyway, good work everyone!