Filed under General , jQuery
This is a nice feature to add to your forms. One of the main reasons you might want to hide a submit button and display a message to the user is to stop them from clicking the button again which, depending on your code, could duplicate a request on the server. This isn't something you want to happen - especially if you're taking payments!
Show or hiding items using jQuery is a breeze but there are a few things you need to watch out for when it comes to showing or hiding submit buttons.
- First thing to watch out for is that if you hide the button then you must make sure to show it again if the page reloads or if the user doesn't go onwards due to any form validation you might be using. This is very important! If you overlook this rule then if someone forgets to fill in a textbox and you prompt them to fill it in, they will not have a button on screen to let them go forward as you hid it when they clicked on it.
- You should always display some sort of message to the user so that they are aware why the button just disappeared. This sounds obvious but if you don't display a message a user might think the form was broken and reload the page after clicking on the button.
So enough of all the doom saying, let's see how to do this! I am doing this example from the point of view of a asp.net developer who uses asp.net form elements. To keep this example simple I am also just posting the details back using a regular asp.net post back. You should be able to expand on this example to include it into your code when handling jQuery AJAX call backs.
Step 1: Setup your HTML
Step 2: Setup your jQuery
//make sure the submit button is visible on page load
//hide the submit button after click and show our loading message
Step 3: Test it out
To see this in action click here. I have the page setup to sleep for 3 seconds on post back to give you time to see the effect in action. A simple message is then displayed in the FormMessage label.
Points to note:
If you are using a MasterPage then you will notice that .net form elements will be given dynamically generated names based on the MasterPage container name and the element name. You should use something like $('[id$=SubmitButton]') to help jQuery 'find' your element within the page. This is slower than finding the element by ID or Class but it's a much neater way than putting in the full generated submit button name and will also work with standard forms!
So that's it. Hopefully you didn't find that too hard to setup and it gives your forms a really nice look on postback and will help you stop users pressing the submit button again and again if your server is a little slow.