0

I have a javascript file that checks the server for results. If it fails to get the results after a certain number of attempts, I want to add a button to the page so the user can manually check for results. However, the button did not work when added. How do I fix it, do I need to do something to get the function in the scope of the button?

This is the code that adds the button:

$('.submitter').after("<span class='btn' onClick=delayDoing(0)>Check again</span>")

Which created the following button that does nothing:

<span class="btn" onclick="delayDoing(0)">Check again</span>

Below is the file of javascript. (I shortened it and removed some of the ERB stuff.)

 function delayDoing(attempts){
     setTimeout(function(){checkServer(attempts)}, 3000);
 }

 function checkServer(attempts){
     if ($('.results').css('opacity') === '0') { //no results           
         if(attempts < 4) {   
             // {code to check for results...}

             delayDoing(attempts+1);
         }
         else{
             $('.submitter').after("<span class='btn' onClick='delayDoing(0)'>Check again</span>")
         }
     }
}

jQuery(function() {
    delayDoing(0)
});
2
  • wrap the function name in quotes: onClick='delayDoing(0)' Commented Oct 9, 2013 at 15:08
  • @levi sorry, fixed. the button does nothing though. Commented Oct 9, 2013 at 15:19

1 Answer 1

1

I would do something like this:

var submit = $('.submitter'); //reference to the submitter button
var newButton = $("<span class='btn'>Check again</span>"); //in-memory button

submit.after( newButton ); //append the button to the DOM
newButton.click(function(){ delayDoing(0); }); //add a click event to the button and call for your function

Remember that javascript is compiled as it's loaded in the browser, since the element didn't exist on compile-time it won't trigger the click event, what you need to do is to append the element to the DOM AND add an event.

Hope this helps, cheers.

Sign up to request clarification or add additional context in comments.

1 Comment

There were some other issues with my code too, but I got it fixed in end. (The $('.results').css('opacity') === '0' wasn't the best condition to use.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.