tags:

views:

5854

answers:

4

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;
});
+5  A: 

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.

SolutionYogi
Thank you for pointing out the obvious! :)
Chris Bartow
no need to run the submit selector twice, you can put that in a var to use within the setTimeout
redsquare
Agreed, modified the code to reflect this approach.
SolutionYogi
A: 

You probably want to wrap the action in a function:

setTimeout(function(){$(this).find(":submit").attr('value', 'Update')}, 2000);
Peter
I think 'this' inside the setTimeout anonymous function won't work correctly. One needs to use closure to capture 'this'.
SolutionYogi
A: 
$("form.stock").submit(function(){
    var $form = $(this);
    $.post( $form.attr('action'), { id: '123', stock: '1' } );
    var $submit = $form.find(":submit").attr('value','Saved!');
    window.setTimeout(function() {
         $submit.attr('value','Update') 
    }, 2000);
    return false;
});
redsquare
+1  A: 

I would suggest, perhaps, a different (in my opinion better) interface to give feedback than changing the text of the button. You could use jGrowl or the dialog widget to display a message via a callback from the post method.

$("form.stock").submit(function(){
    $.post(
        $(this).attr('action'),
        { id: '123', stock: '1' },
        function() { $.jGrowl("Your update was successfully saved."); }
    );
});
tvanfosson
+1 for talking usability (feedback)
karim79