I am new to JS and facing some challenges which may seem simple.
what i want to do is:
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);
});
                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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With