10

I have an HTML form with multiple inputs. Some have the class required.

I want to show the "submit" button once all of these fields have a value.

I tried using:

$(document).ready(function() {
    $("#submit_button").hide();

    $('.required').on('keyup', function () {
        if($(this).val() !== "") {
            $("#submit_button").show();
        } else {
            $("#submit_button").hide();
        }
    });
});

but this shows the button if just one input is not blank.

Is it possible to do this for multiple inputs, once all the inputs with the required class are not blank?

CheckRequired function

function CheckRequired(event) {
    var $form = $(this);

    var emptyElements = $form.find('.required').filter(function() {
        return this.value === ''
    });

    if(emptyElements.length > 0) {
        event.preventDefault();

        emptyElements.addClass("EmptySelect").attr('title', 'This field is required');

        //alert(emptyElements.attr("id"));
        alert("One or more fields cannot be blank");

        event.stopImmediatePropagation();
        return false;
    }
}
charlie
  • 415
  • 4
  • 35
  • 83
  • Check this: http://stackoverflow.com/questions/5614399/disabling-submit-button-until-all-fields-have-values – AndrewL64 Mar 07 '16 at 09:36

8 Answers8

6

You have to check all required input on keyup with a loop:

<script type="text/javascript">
$(document).ready(function() {
    $("#submit_button").hide();

    $('.required').on('keyup', function () {
        var showBtn = true;
        // Check all inputs
        $('.required').each(function () {
            showBtn = showBtn && ($(this).val() !== "");
        }); //Edited
        // Hide or show the button according to the boolean value
        $("#submit_button").toggle(showBtn);
    });
});
</script>
KUTlime
  • 5,889
  • 1
  • 18
  • 29
Finrod
  • 2,425
  • 4
  • 28
  • 38
  • i am trying to use this however its telling me `showBtn` is false using `alert(showBtn);` . I have one text input with a class of required and when i type in the input, it alerts saying `false` – charlie Jul 28 '16 at 12:50
  • Hi @charlie, can you post a JsFiddle with your code and the `alert` line? It will be easier to understand what's wrong. – Finrod Jul 28 '16 at 13:18
  • Adding jquery in your JsFiddle make it works correctly : https://jsfiddle.net/jxozk956/1/ – Finrod Jul 28 '16 at 14:04
  • i see the fiddle is working, but in my code it doesn't seem to be. still showing false – charlie Jul 28 '16 at 15:39
  • If you have the same code, it may be something else in your application that make this script not working. I can't help you without more information, please edit you question to add more snippets (or ask another question). – Finrod Jul 28 '16 at 15:50
5

The logic is straightforward:

  1. Assume we'll show the button.
  2. Look at each required input.
  3. If any of those is empty, we need to hide the button, and don't need to check any more inputs.

And don't just watch keyup. That won't catch data pasted in via mouse/etc. I'd also watch change and blur, to be safe.

$(document).ready(function() {
  // show submit button *only* when all
  // .required fields have a value
  //
  var checkRequired = function() {
    var allValid = true;   // assume we're ready

    $('.required').each(
      function() {
        if (this.value.trim() === "") {
          // fail as soon as we hit an empty field
          allValid = false;
          return false;    // this ends the each() loop
        }
      }
    );

    $('#submit_button').toggle(allValid);
  }

  $('.required').bind('keyup change blur', checkRequired);
  
  checkRequired();  // start off in a correct state
});
.required {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <input type="text" class="required" />
  <input type="text" />
  <input type="text" class="required" />
  <input type=submit id=submit_button value="Submit" />
</form>

Note that we call checkRequired() at startup, so that if the fields already have values, we'll show the button appropriately.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
2

Try like this:

<script type="text/javascript">
  $(document).ready(function() {
    $("#submit_button").hide();

  $('.required').each('keyup', function () {
    if($(this).val() !== "") {
        $("#submit_button").show();
    } else {
        $("#submit_button").hide();
    }
  });
});
</script>
Sumanta736
  • 695
  • 3
  • 10
1
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var flag = true;
            $('.required').keyup(function () {
                $('.required').each(function (index, responce) {
                    if ($(this).val() == "") {
                        flag = false;
                        return;
                    }
                    else {
                        flag = true;
                    }
                });
                if (flag == true) {
                    $('#submit').show();
                }
                else {
                    $('#submit').hide();
                }
            });
        });
    </script>
</head>
<body>
    <input type="text" name="name" value="" class="required" />
    <input type="text" name="name" value="" class="required" />
    <input type="text" name="name" value="" class="required" />
    <input type="text" name="name" value="" class="required" />
    <input type="text" name="name" value="" class="required" />
    <input type="submit" id="submit" style="display:none;" />
</body>

</html>
0

Users generally don't access multiple controls at a time. More importantly, events are processed one at a time. So you can just use a counter to check whether all required fields have been filled out, without needing to check all fields on every keyup event. You just need to keep track of whether a field was valid before, in order to not mess up the counter. Here is an efficient and effective solution:

<script type="text/javascript">
$(document).ready(function() {
    var button = $('#submit_button');
    var required = $('.required');
    var counter = 0;
    var trigger = required.length;
    button.hide();

    required.on('keyup', function () {
        var self = $(this);
        if(self.val() !== '') {
            if (!self.data('valid') && ++counter === trigger) button.show();
            self.data('valid', true);
        } else {
            if (self.data('valid')) --counter;
            button.hide();
            self.data('valid', false);
        }
    });
});
</script>

Fiddle: https://jsfiddle.net/fa1LsLfh/1

Julian
  • 4,176
  • 19
  • 40
  • Okay, i have tested and got it working changed my `required` class to something else. i think the issue is to do with another function as when i remove this, its starts to work fine. see the function called `CheckRequired` in my question – charlie Aug 01 '16 at 07:29
  • What starts to work fine when you remove what? What is your question? I am glad to help but please be more specific. – Julian Aug 01 '16 at 08:26
  • I have a function called `CheckRequired` which i have put into my original question. when i remove this function, your code starts to work fine. – charlie Aug 01 '16 at 10:35
  • Just from the code posted here, I see no reason why these functions should interact. Could you show the full code? – Julian Aug 01 '16 at 11:21
0

Can you try this code. It will work for you

$(document).ready(function() {
    $("#submit_button").hide();

    $('.required').on('keyup', function () {                    
           ToggleSubmitButton();
    }); 
});

function ToggleSubmitButton()
{
    $("#submit_button").hide();
    var getRequiredLength = $('.required').length;
    var nonempty = $('.required').filter(function() {
        return this.value != ''
    }).length;

    if(getRequiredLength ==  nonempty){
        $("#submit_button").show();
    }

}
Parithiban
  • 1,656
  • 11
  • 16
  • While this code may answer the question, providing additional context regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. – Božo Stojković Jul 31 '16 at 19:43
0

If your inputs are truly required you can use the :invalid pseudo-class to fetch all required fields that are empty, if that collection's length is <1 you know all required fields have been filled. If they only got the class required you could use JS to set the property too. This also works for all other validated fields like email fields or stuff, so I would prefer this method. Here is an example of how it works:

jQuery(document).ready(function() {
  jQuery('#testform input').on('keyup', function() {
    if(jQuery('#testform input:invalid').length < 1)
      {
        jQuery('#testform .dependend_submit').show();
       }
    else
      {
        jQuery('#testform .dependend_submit').hide();
      }
  });
});
.dependend_submit {display: none;}
input {display: block;}
input:required {border-left: 1px solid red;}
input:not(:required) {border-left: 1px solid blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testform">
  <input type="text" name="text1" required="required" />
  <input type="text" name="text2" required="required" />
  <input type="text" name="text3" />
  <input type="text" name="text4" required="required" />
  <input type="text" name="text5" required="required" />
  <input type="submit" name="submit" value="submit" class="dependend_submit" />
user3154108
  • 1,264
  • 13
  • 23
0

I just came across this question. Let me add another approach to handle this.

HTML

<form>
  <input type="text" name="a" value="" required>
  <input type="text" name="b" value="" required>
  <input type="submit" id="submit_button" disabled>
</form>

CSS

#submit_button {
  display: none;
}

#submit_button.active {
  display: inline;
}

JavaScript

var submit = $('#submit_button'),
    required = $('input[required]');

required.on('keyup', function() {
    if (0 == required.filter(function() { return '' == this.value; }).length) {
        submit.addClass('active').prop('disabled', false);
    }
});

How it works

  • The submit button is hidden by default using CSS. This avoids that it might flash shortly, when the page is loaded. It is also disabled.
  • The required input fields have the attribute required, which might also show a browser validation info, if the input is empty. This is an alternative to using the class .required. You can still alter the selector from input[required] to .required of course.
  • The submit button as well as all required fields are stored in variables (submit and required). This is to avoid a lot of re-querying on each keyup event handler.
  • Finally on each keyup the previously selected inputs are filtered for empty values. If the result is empty (0 == list.length), the button is shown by adding a CSS class active (could be named enabled or similar as well of course). This has the advantage that you could add things like a transition etc. easily. It also enhances decoupling of your CSS and JavaScript.

Final thoughts

Using keyup might work on simply text inputs. If you have other inputs you want to track, like checkboxes, select dropdown etc., you might consider using .on('input change') on the form itself instead.

You could also disable and hide the button as well, if a field becomes empty again, like:

if (0 == required.filter(function() { return '' == this.value; }).length) {
  submit.addClass('active').prop('disabled', false);
} else {
  submit.removeClass('active').prop('disabled', true);
}

Demo

Try before buy

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126