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.

ruben (Sat, 01/28/2012 - 12:22)

Permalink
thanks for example

toplu mail (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.

Mat (Tue, 03/07/2017 - 05:07)

Permalink

The text changes, however, the button does not work anymore.

Jason (Mon, 05/04/2020 - 13:02)

Permalink

Yes, the function returns false, which means the function will prevent the form from submitting.

If you want to allow the form to submit you can do something like this:

  1. var buttonClicked = false;
  2.  
  3. function changeText(submitId) {
  4. if (buttonClicked == false) {
  5. var submit = document.getElementById(submitId);
  6. submit.value = 'Loading...';
  7. buttonClicked = true;
  8. return false;
  9. } else {
  10. return true;
  11. }
  12. }

 

philipnorton42 (Mon, 05/04/2020 - 14:30)

Add new comment

The content of this field is kept private and will not be shown publicly.