5

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?

$(document).ready(function (){
    validate();
    $('input').on('keyup', validate);
});

function validate(){
    if ($('input').val().length > 0) {
        $("input[type=submit]").prop("disabled", false);
    } else {
        $("input[type=submit]").prop("disabled", true);
    }
} 
brewpixels
  • 311
  • 1
  • 5
  • 19

8 Answers8

10

Here's a modification of your code that checks all the <input> fields, instead of just the first one.

$(document).ready(function() {
  validate();
  $('input').on('keyup', validate);
});

function validate() {
  var inputsWithValues = 0;
  
  // get all input fields except for type='submit'
  var myInputs = $("input:not([type='submit'])");

  myInputs.each(function(e) {
    // if it has a value, increment the counter
    if ($(this).val()) {
      inputsWithValues += 1;
    }
  });

  if (inputsWithValues == myInputs.length) {
    $("input[type=submit]").prop("disabled", false);
  } else {
    $("input[type=submit]").prop("disabled", true);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
rphv
  • 5,409
  • 3
  • 29
  • 47
4

Vanilla JS Solution.

In question selected JavaScript tag.

HTML Form:

<form action="/signup">
    <div>
        <label for="username">User Name</label>
        <input type="text" name="username" required/>
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" />
    </div>
    <div>
        <label for="r_password">Retype Password</label>
        <input type="password" name="r_password" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email" />
    </div>
    <input type="submit" value="Signup" disabled="disabled" />
</form>

JavaScript:

var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
    var disabled = false
    inputs.forEach(function(input, index) {
        if (input.value === '' || !input.value.replace(/\s/g, '').length) {
            disabled = true
        }
    })
    if (disabled) {
        register.setAttribute('disabled', 'disabled')
    } else {
        register.removeAttribute('disabled')
    }
})

Some explanation:

In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.

If you need to disable submit button until all required input fields are filled in - replace:

inputs.forEach(function(input, index) {

with:

required_inputs.forEach(function(input, index) {

where required_inputs is already declared array containing only required input fields.

JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/

Mikhail
  • 11,067
  • 7
  • 28
  • 53
0

You could try using jQuery Validate

http://jqueryvalidation.org/

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

And then do something like the following:

$('#YourFormName').validate({
    rules: {
        InputName1: {
            required: true
        },
        InputName2: { //etc..
            required: true
        }
    }
});
Blue Boy
  • 620
  • 1
  • 6
  • 13
0

Refer to the sample here.

In this only input of type="text" has been considered as described in your question.

HTML:

<div>
    <form>
        <div>
            <label>
                Name:
                <input type="text" name="name">
            </label>
        </div>
        <br>
        <div>
            <label>
                Age:
                <input type="text" name="age">
            </label>
        </div>
        <br>
        <div>
            <input type="submit" value="Submit">
        </div>
    </form>
</div>

JS:

$(document).ready(function () {
    validate();
    $('input').on('keyup check', validate);
});

function validate() {
    var input = $('input');
    var isValid = false;
    $.each(input, function (k, v) {
        if (v.type != "submit") {
            isValid = (k == 0) ?
              v.value ? true : false : isValid && v.value ? true : false;
        }
        if (isValid) {
            $("input[type=submit]").prop("disabled", false);
        } else {
            $("input[type=submit]").prop("disabled", true);
        }
    });
}
Shashank
  • 2,010
  • 2
  • 18
  • 38
0

Try to modify your function like this :

function validate(){
    if ($('input').val() != '') {
        $("input[type=submit]").prop("disabled", false);
    } else {
        $("input[type=submit]").prop("disabled", true);
    }
} 

and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :

<input type = "text" name = "test" id = "test" onkeyup = "validate();">

Not so sure of this but it might help.

JanLeeYu
  • 981
  • 2
  • 9
  • 24
0

Here is a dynamic code that check all inputs to have data when wants to submit it:

    $("form").submit(function(e) {
      var error = 0;
      $('input').removeClass('error');
      $('.require').each(function(index) {
        if ($(this).val() == '' || $(this).val() == ' ') {
          $(this).addClass('error');
          error++;
        }
      });

      if (error > 0) {
        //Means if has error:
        e.preventDefault();
         return false;
      } else {
        return true;
      }


    });
.error {

  border: 1px solid red;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<form>

  <form action="google.com">
    <input type="text" placeholder="This is input #1" class="require" />
    <input type="text" placeholder="This is input #2" class="require" />
    <input type="submit" value="submit" />
  </form>


</form>

Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!

Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
0

Modify your code

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
    <input type="text"><br>
    <input type="text"><br>
    <input type="text"><br>
    <input type="submit" value="Join">

    <script>
    $(document).ready(function (){
        validate();
        $('input').on('keyup', validate);
    });

    function validate(){

        $("input[type=text]").each(function(){
            if($(this).val().length > 0)
            {
                $("input[type=submit]").prop("disabled", false);
            }
            else
            {
                $("input[type=submit]").prop("disabled", true);
            }
        });
    } 
    </script>
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20
-1

function disabledBtn(_className,_btnName) {
 var inputsWithValues = 0;
 var _f = document.getElementsByClassName(_className);
 for(var i=0; i < _f.length; i++) { 
  if (_f[i].value) {
    inputsWithValues += 1;
  }
 }  
  if (inputsWithValues == _f.length) {
    document.getElementsByName(_btnName)[0].disabled = false;
  } else {
    document.getElementsByName(_btnName)[0].disabled = true;
  }
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">
Sky Blue
  • 1
  • 1