Greasemonkey: Why does this if statement always return true?

245
December 10, 2016, at 2:50 PM

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);
Answer 1

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.

READ ALSO
Returning html as ajax response

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download...

332
Draggable not working after using jquery load function

Draggable not working after using jquery load function

I'm creating a html builder for my project which including importing a template and edit via drag and dropI used jquery's load() function to import template to my console page

369
Add multiple DateTime Duration strings together using JavaScript to get total duration

Add multiple DateTime Duration strings together using JavaScript to get total duration

I have an HTML Table used to generate a Calendar which shows TimeClock entries for each day a user has worked and clocked in and out of the systemEach day also shows the total time duration for each clock in/out entry

371
Call Code behind method using ajax

Call Code behind method using ajax

I am calling my static web method from html page using ajaxbut it doesn't hit my method rather it reload the page

370