Javascript help – disable form button until both "input" and "textarea" are filled

Advertisements

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);
        }
    });

} 

>Solution :

You can do something like this.

$(document).ready(function() {
  validate();
  $('.form-control').on('keyup', validate);
});


function validate() {
  let isValid = true;
  $(".form-control").each(function() {
    if ($(this).val() == "") {
      isValid = false;
    }
  });
  
  if (isValid) {
    $("button[type=disabled-on-empty-form]").prop("disabled", false);
  } else {
    $("button[type=disabled-on-empty-form]").prop("disabled", true);
  }

}

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.

Leave a ReplyCancel reply