Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery setTimeout() Function [duplicate]

Tags:

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" class="submit_wide" id="myBtn" >
</form>

javascript

$(".submit_wide").click(function () {
    $(this).val('Please wait..');
    $(this).attr('disabled', true);
    setTimeout(function() { 
        $(this).attr('disabled', false);
        $(this).val('Submit');
    }, 2000);
});
like image 632
ARTLoe Avatar asked May 07 '15 16:05

ARTLoe


1 Answers

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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" class="submit_wide" 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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" class="submit_wide" value="Submit"/>
like image 160
Dave Avatar answered Sep 20 '22 18:09

Dave