Change Text Of Submit Button When Clicked

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.

<form action="" method="get">
<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;
</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.

<script type="text/javascript"> 
    function changeText(submitId){
        var submit = document.getElementById(submitId);
        submit.value = 'Loading...';
        return false;
    };
</script>

 

Comments

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.

Permalink
thanks for example
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.
Permalink

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

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:

var buttonClicked = false;

function changeText(submitId) {
  if (buttonClicked == false) {
    var submit = document.getElementById(submitId);
    submit.value = 'Loading...';
    buttonClicked = true;
    return false;
  } else {
    return true;
  }
}

 

Name
Philip Norton
Permalink

sir can we do this button change text for some particular time period and after that time period the text will be same as the before we clicked??

Permalink

Yes, you'll need to use the setTimeout() function to do that.

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
20 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.