Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  129] [ 4]  / answers: 1 / hits: 27385  / 12 Years ago, tue, november 27, 2012, 12:00:00

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?


More From » jquery

 Answers
12

Do a typeof to know the types of your values.



console.log(typeof $(this).val());
console.log(typeof txt.value);





jQuery could have altered the values when using .val() like trim whitespaces that should be present. To make sure, you can avoid using val().



The this in .each() as well as the second argument is the DOM element per iteration. You could get the value of the option directly:



$('select > option').each(function(i,el){
//we should be getting small caps values
console.log(this.value);
console.log(el.value);
});





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:



12    ==  12  // true
12 == 12 // true; tested on Firefox 20 (nightly)
12 === 12 // false





At this point, we have weeded all thinkable gotchas. If none worked, both could be totally different values in the first place.


[#81783] Sunday, November 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brookelynshaem

Total Points: 468
Total Questions: 98
Total Answers: 101

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;