I have a form containing various fields.
See jsFiddle demo.
My aim is to enable the submit button only when the user has filled in all fields.
So far, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.
jQuery("input[type='text']").on("keyup", function () {
if (jQuery(this).val() != "" ) {
if (jQuery("#titlenewtide").val() != '')
{
jQuery("#subnewtide").removeAttr("disabled");
}
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Note that I am loading the JavaScripts in my footer.
Thought I might chip in. Assuming as little as possible.
Why don't you use jquery validate . It's a good plugin .
The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.
Fiddle
Here's how you can do it:
By far the easiest, would be to rely on the HTML5 validation you're already using.
You'd have to add
required
to all form controls if you want to require all of them, and that can easily be done by using jQuery's:input
selector and setting the property, like soWe'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.
Then we'll listen for the
input
event, which covers all sorts of inputs, like typing, pasting etc, and thechange
event as well to cover the radio button.Using
form.checkValidity()
tells us if the form is valid, and returns a boolean, so we could use it directly to set thedisabled
property of the submit button.All together it looks like this, and that's all you need, a few lines of really simple code
FIDDLE
If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill
There's actually a pretty easy approach. I'm using native JavaScript, but I think it is applicable in jQuery as well:
The change event on form is always called, when any input or textarea element was changed (click in element, type, click somewhere else or lose focus).
Edit:
Regarding hidden fields, you can exclude them by surrounding the enable calculation with an if-condition:
Note:
This will work in any browser (even Internet Explorer 5.5). Check on MDN:
for ..in Loop
element.getElementsByTagName()
document.getElementById()