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.
Try utilizing
.siblings()
,.map()
to compile values ofform
elements ,Array.prototype.every()
to returnBoolean
representation ofinput
,textarea
values , setdisabled
property ofform input[type=submit]
elementOn each
input
change, test the values of otherinputs
and checked state ofradio
, if allinputs
has been entered it will make the submitbutton
enabled:Demo:
Also it uses the form
id="myForm"
, so you can use it to validate only specific forms in your pages.Note: This is tested and working on
Chrome
,Firefox
andIE
.EDIT:
In the previous code we are using
onchange
event handler to call the function so it's only called when we click outside a given input (after change).To perform the call automatically when the user enters a character in a field (the last one) we need to use the
onkeyup
event so we don't need to click outside of it.This is the changed code you need :
My solution is base on standard JavaScript.
HTML form
JavaScript
Use this code below. On each input, it will check all the form fields by using this function
validate()
.Fiddle
Update
To make it validate if the form has
id="new_tide"
and fix about theradio
button.Fiddle
Here is a quick way to accomplish that. It involves attaching a
change
event listener to:radio
and:checkbox
elements and aninput
event listener to other elements. These can both use a common predefinedhandler
that will count the number ofunfilled
element each time each of these events fires on the appropriate element.