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" /> </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.
The text changes, however, the button does not work anymore.
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; } }
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??
Yes, you'll need to use the setTimeout() function to do that.