Change Text Of Submit Button When Clicked

Friday, March 19, 2010 - 16:11

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
2
3
4
5
<form method="get" action="">
    <label for="textinput">Text:</label> 
    <input type="text" value="" name="textinput" id="textinput" /> 
    <input type="submit" id="submitbutton" value="Search" onclick="return changeText('submitbutton');" /> 
</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
2
3
4
5
6
7
<script type="text/javascript"> 
    function changeText(submitId){
        var submit = document.getElementById(submitId);
        submit.value = 'Loading...';
        return false;
    };
</script>
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

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.

thanks for example

Add new comment