Change Text Of Submit Button When Clicked

19th March 2010

Changing the text of a submit button when clicked can be useful if you are writing an AJAX application or you know that there will be some sort of delay. Providing the user with some form of feedback is a useful way of letting them know they they have done something.

First, we need a form to work with, so I built a quick one here. Notice that the submit button has an onclick action associated with it, this will be used later to enable us to alter the text of the button.

  1. <form action="" method="get">
  2. <label for="textinput">Text:</label> <input id="textinput" name="textinput" type="text" value="" /> <input id="submitbutton" onclick="return changeText('submitbutton');" type="submit" value="Search" />&nbsp;
  3. </form>

The following JavaScript block defines the function that changes the text of the submit button. The function just looks up the input element and changes the value of it to "Loading...". This function returns false, which causes the button not to submit the form. This can be changed to true if you want the form to be submitted when the button is pressed.

  1. <script type="text/javascript">
  2. function changeText(submitId){
  3. var submit = document.getElementById(submitId);
  4. submit.value = 'Loading...';
  5. return false;
  6. };
  7. </script>

 

Comments

Permalink

It is an excellent tutorial on how to change text of submit button when clicked and can be useful if you are writing an AJAX application or you know that there will be some sort of delay. I appreciate the nice work.

Submitted by ruben on Sat, 01/28/2012 - 12:22

Permalink
thanks for example

Submitted by toplu mail on Sun, 01/22/2017 - 14:24

Permalink
Thanks for this, Philip. Is there a way to change the contents of the 'textinput' field AND submit the form upon clicking 'Search'? I want to display a new message within the form field itself to confirm that the form was sent.

Submitted by Mat on Tue, 03/07/2017 - 05:07

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.