Using jQuery to change the text of an enter button in a few seconds

I use form and jQuery to quickly change website. I would like to change the button text to "Saved!". then change it to โ€œRefreshโ€ after a few seconds so that the user can change the value again. Of course, they can hit โ€œSaved!โ€, But that doesn't look very good.

$("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; }); 
+7
jquery forms
source share
5 answers

The first argument to setTimeout is a function. So wrap your code inside an anonymous function, and you're 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 can not check this code right now. Let me know if this doesn't work.

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

+13
source share

If this is really a "button" tag, then you would use it to change it.

 $('#button_id').html('New Text'); 

Of course, if you create this onClick button for this button, you can simply simply pass (this) to the function as an object and $ (this) .html ('New Text'); instead of this.

Hope this helps someone.

+6
source share

I would suggest, perhaps, a different (in my opinion, better) interface to give feedback than changing the text of a button. You can use jGrowl or dialog to display the message through 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."); } ); }); 
+2
source share

You probably want to transfer the action to a function:

 setTimeout(function(){$(this).find(":submit").attr('value', 'Update')}, 2000); 
0
source share
 $("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; }); 
0
source share

All Articles