Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 🙁

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading