When I do the following comparison I get false although both val() and value visually display the same value:12
if ($(this).val() == txt.value)//returns false
When I alert both $(this).val() and txt.value I get 12. Is one of them a string and the other one an int? If so, which one’s what?
Do a
typeofto know the types of your values.jQuery could have altered the values when using
.val()like trim whitespaces that should be present. To make sure, you can avoid usingval().The
thisin.each()as well as the second argument is the DOM element per iteration. You could get the value of theoptiondirectly:When using loose comparison (
==), number 12 and string 12 should be the same. Even more surprising is that it’s true even with the string having whitespaces around it. But with strict comparison (===), they shouldn’t be:At this point, we have weeded all thinkable gotchas. If none worked, both could be totally different values in the first place.