Search code examples
javascriptjqueryif-statementgreasemonkey

Greasemonkey: Why does this if statement always return true?


This confuses me... I'm using waitforkeyelements on an ajax page... I have an if statement that should only pop up an alert if there is a button with the value "Accept Offer". Unfortunately, it's popping the alert when the only 2 buttons have values of "Continue Exploring" and "Invest". I have a feeling it has something to do with true/false stuff, but I can't figure out why getElementById is supposed to work used like this but my selector doesn't. This DOES work if I add an ===something but I want to know why it doesn't work like this.

So, when there are 2 buttons that have values of "Continue Exploring" and "Invest", I get an alert that says "Yes!" and then an alert that says "Invest". Shouldn't it run the "else" when there isn't a button with the value "Accept Offer"?

function countit () {

  if ($( '.adv-action[value*="Accept Offer"]')){

    alert("Yes!")
    alert($('.adv-action').val())

   }

  else{
    alert("no")
    alert($('.adv-action').val())
   }
}

waitForKeyElements ('[value*="Continue Exploring"]', countit);

Solution

  • You should do

    if ($( '.adv-action[value*="Accept Offer"]').length!=0){
    
        alert("Yes!")
        alert($('.adv-action').val())
    
       }
    
    else{
        alert("no")
        alert($('.adv-action').val())
    }
    

    $( '.adv-action[value*="Accept Offer"]') returns an array and array will always equate to true, so check if it actually contains any element or not by equating its length to 0.