I have a small script disabling a form button until all inputs in my HTML are filled. I would like to also have "textarea" HTML be filled for the form button to be enabled.
In other words, the form button must be enabled if both "input" and "textarea" are filled in, not just "input".
I’m an absolute beginner with JS 🙁
This is the code I have:
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[class=form-control]").each(function(){
if($(this).val().length > 0)
{
$("button[type=disabled-on-empty-form]").prop("disabled", false);
}
else
{
$("button[type=disabled-on-empty-form]").prop("disabled", true);
}
});
}
3
Answers
First, add
textarea
to the selector. In addition, use a boolean flag to store if any input was not filled and only disable the button at the end of the loop.You can do something like this.
Give each control a class of ‘form-control’. So all your input and textarea will have this class.
Note: Button element type should be either submit, button, or reset. You should add something like id or class to get the button element.
HTML has validation built in to prevent the form from being submitted, no JavaScript required. Just add the required attribute.
If you want to fix your code, you should only be disabling the form when you find the issue since you have multiple elements. You code is undoing the last check.