0

I have this problem. I am trying to make a button "click it self" using a setTimeout function in javascript. I need this small piece of code to function to be able to simulate a refresh. The problem is, because the button on which I'm calling the refresh is within a form tag, this operation only occurs once, instead of continuously repeating itself. Here is my javascript

<script language="javascript" type="text/javascript">

function ClickMe(){
        setInterval('document.getElementById("auto").click()',5000);
        alert("Function works");
 }

</script>

Here is the element on which I am calling it.

<form>
  <input id="auto" type="submit" value="Click" onClick="ClickMe()" />   
</form>

If you remove the "<form></form>" tag, the code runs normally by calling itself again and again every 5 seconds. Byt once you add the "<form>" tag, the function is only called once. If someone could help me out, I'll be really grateful. Thanks

MacMac
  • 34,294
  • 55
  • 151
  • 222
user3295929
  • 61
  • 1
  • 3
  • Because the `
    ` has already been submitted and page refreshes thus, refreshes the script (the previous `setInterval()` would of been, in layman terms: *"forgotten"* ), a quick question though - *why* would you want to do this?
    – MackieeE Feb 12 '14 at 10:45
  • you could keep another button outside the form.. –  Feb 12 '14 at 10:46
  • Actually, i'm working on a project in groovy and grails, and I'm facing a similar problem whem using the /. What I'm trying to do is to update a section of my page after clicking a button once, over and over again as a way of implemeting dynamic display. The update works, but now I've to find a way of automatically refreshing the section of the page – user3295929 Feb 12 '14 at 11:04

2 Answers2

1

For whatever reason you want to do this, just change your submit to a button like so:

<input id="auto" type="button" value="Click" onClick="ClickMe()" />

also, you should note that you're going to keep creating more and more intervals for this each time it's ran.

Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • It seems the main issue is with the input type as you've suggested. I would like to ask, isn't there a way of making this work with a button of type "submit" ? – user3295929 Feb 12 '14 at 11:54
0

When you wrap the input with form, the form is submitted, you can avoid that by returning false in the ClickMe function.

function ClickMe(){
    setInterval('document.getElementById("auto").click()',5000);
    alert("Function works");
    return false;
}
Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19