Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to change input button text back after a few seconds

Tags:

jquery

forms

I'm using a form and jQuery to make a quick change on a web site. I would like to change the button text to 'Saved!' then change it back to Update after a few seconds so the user can change the value again. Of course they can hit the now 'Saved!' button again, but it doesn't look nice.

$("form.stock").submit(function(){
    // Example Post
    $.post($(this).attr('action'), { id: '123', stock: '1' });
    $(this).find(":submit").attr('value','Saved!');
    // This doesn't work, but is what I would like to do
    setTimeout($(this).find(":submit").attr('value','Update'), 2000);
    return false;
});
like image 431
Chris Bartow Avatar asked Jul 01 '09 19:07

Chris Bartow


1 Answers

First argument to setTimeout is function. So wrap your code inside an anonymous function and you are good to go.

$("form.stock").submit(function(){
    // Example Post
    $.post($(this).attr('action'), { id: '123', stock: '1' });
    var submit = $(this).find(":submit").attr('value','Saved!'); //Creating closure for setTimeout function. 
    setTimeout(function() { $(submit).attr('value','Update') }, 2000);
    return false;
});

I am not able to test this code right now. Let me know if it doesn't work.

EDIT: As suggested by redsquare, it makes sense to create closure from the submit button itself.

like image 85
SolutionYogi Avatar answered Oct 16 '22 00:10

SolutionYogi