jQuery Snippets: How to Conditionally Enable Submit
One easy way to prevent users from submitting an empty form in a pinch is to conditionally disable the submit button. This might be technically be considered a best practice, but if you're in a rush and don't have the time to write an entire set of validation rules, this is a solution (even if it's only a temporary one), that works.
Here's how it works. First, you'll need to disable the attribute in your HTML. This is actually pretty simple and straightforward, all you really need to do is add the disabled attribute (simply the word "disabled", or, if you're using XHTML disabled="disabled") to your element's HTML. See the snippet below for an example:
<input type="submit" id="submit" value="Submit" disabled>
Then, in your jQuery, you'll add some simple code that will conditionally remove the disabled attribute.
The jQuery code uses the .keyup() event method to verify that the user did press at least one key in the selected input field (in the case of the code snippet below, we're selecting the #name input field -- so that means that the submit button won't be enabled until something is entered in the name field). Then, we use the .attr() method to remove the disabled attribute value from the submit field, thus enabling it and allowing our user to submit the form.
To see it in action, check out the jQuery code snippet below:
$('#name').keyup(function() { $('#submit').attr('disabled', !$('#name').val()); });
Like we already said, this method of "validation" (we use that term loosely) is hardly a best practice, but it'll get the job done in a pinch. Plus, if you're new to jQuery, just playing around with this code snippet is a good way to get a handle on both the .keyup() and .att() methods, while also getting some exposure to HTML attributes and how you can use jQuery to manipulate them.
Happy coding!