Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

How to compare jQuery val() and JavaScript value

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?

Upvotes: 3

Views: 28086

Answers (2)

Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

I feel obliged to write so comments, which I find very useful, after taking so much time of the guys around here. So my problem was this:

('#mySelect option').each(function({
  if ($(this).val() == txt.value)
    return;
});
alert('Code still continues');

Although the result of the condition $(this).val() == txt.value was true the code after the each loop still executed. That's why I thought that the two values did not match. But if I put an alert inside this condition it showed up. It means something wrong was with the behavior of "return" inside the each loop. I've lately come to understand that although return stops the execution of the code after itself inside the each loop, it does not prevent the code from executing after the each block. Thus, to achieve the full function return inside the jquery each loop we seem to have to put a flag and decide if to return after the each according to this flag. The following code worked for me:

var shouldContinue = true;
('#mySelect option').each(function ()
{
    if ($(this).val() == txt.value) {
        shouldContinue = false;
        return (false);
    }
});
if (!shouldContinue)
    return; 

Note return(false) inside the iteration. What this means is, if the condition is true continue iterating no more and leave the loop.

Upvotes: 0

Joseph
Joseph

Reputation: 119837

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.

Upvotes: 8

Related Questions