jQuery setTimeout() Function [duplicate]

I am new to JS and facing some challenges which may seem simple.

what i want to do is:

  1. a user clicks on a button that states 'submit'
  2. when the button is clicked the word 'submit' changes to 'please wait...' & button is disabled
  3. the button is disabled for 2 seconds
  4. after 2 seconds the word 'please submit..' changes back to 'submit' & the button becomes activated (its no longer disabled)

i have written the below code. Any advise on this would be much appreciated

html

<form action="#" method="post"> <input type="button" name="submit" value="Submit" >
</form>

javascript

$(".submit_wide").click(function () { $(this).val('Please wait..'); $(this).attr('disabled', true); setTimeout(function() { $(this).attr('disabled', false); $(this).val('Submit'); }, 2000);
});
2

1 Answer

The problem is that inside the setTimeout() call, this doesn't refer to the button. You need to set a variable to keep the reference to the button.

I've created a sample below. See how I use the variable named $this.

$(".submit_wide").click(function () { var $this = $(this); $this.val('Please wait..'); $this.attr('disabled', true); setTimeout(function() { $this.attr('disabled', false); $this.val('Submit'); }, 2000);
});
<script src=""></script>
<input type="button" value="Submit"/>

UPDATE:Now with modern browsers supporting Arrow Functions, you can use them to avoid altering the this context. See updated snippet below.

$(".submit_wide").click(function () { $(this).val('Please wait..'); $(this).attr('disabled', true); setTimeout(() => { $(this).attr('disabled', false); $(this).val('Submit'); }, 2000);
});
<script src=""></script>
<input type="button" value="Submit"/>
0

You Might Also Like