0

How can I check the Number of Incomplete Input fields in Particular ID, (form1, form2). If 2 input fields are empty, in i want a msg saying something like "Incomplete Input 2" How is it Possible to do this in JS ?

<div id="form1">
 <span>Number of Incomplete Input: 2</span>
 <input type="text" value="">
 <input type="text" value="">
</div>

<div id="form2">
 <span>Number of Incomplete Input: 1</span>
 <input type="text" value="Test">
 <input type="text" value="">
</div>

This is the JS, which is working, i have have multiple JS with class named assigned to each inputs and get the value, but i need to make this check all the Input fields inside just the ID.

$(document).on("click", "#form1", function() {
            
        var count = $('input').filter(function(input){
            return $(this).val() == "";
        }).length;

        alert(count);
        
    });
5
  • what have you tried so far ? Please show us your attempt Commented Sep 5, 2020 at 10:28
  • 1
    Why JavaScript? <form validate><input type="text" required /></form> Commented Sep 5, 2020 at 10:28
  • @Andreas Thats what OP said => i want a msg saying something like Incomplete Input 2 Commented Sep 5, 2020 at 10:29
  • Is there no <form> element around them all? i feel there is missing important HTML here we need to know about Commented Sep 5, 2020 at 10:30
  • try this selector input:not([value]):not([value=""]) which will select all the inputs that has no value attributes or empty one, then check the length Commented Sep 5, 2020 at 10:40

3 Answers 3

1

Your html structure, especially form structure is not correct, so you should first add some submit button to form that can be clicked. Then you can add event listener on form's submission. In the event handler you should select children inputs inside the form tag using $(this).children("input"). Now you can filter them.

$(document).on("submit", "#form1", function (e) {
  e.preventDefault();
  var count = $(this)
    .children("input")
    .filter(function (input) {
      return $(this).val() == "";
    }).length;

  alert(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
    <span>Number of Incomplete Input: 2</span>
    <input type="text" value="">
    <input type="text" value="">
    <button type="submit">Submit</button>
</form>

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe also use the trim() method to avoid empty space being as valid.
thankyou, but how can i add the value inside Span rather than alert
@BalZankar You can change it using $(this).children("span").html("Number of Incomplete Input: " + count); Just put this code instead of alert(count);
0

This is the JS, which is working, if I have have multiple JS with class named assigned to each inputs and Im getting the value, but i have multiple JS for this to work.

How can i make this Simpler say like, when user clicks on Div, it only checks the input fields inside that div.

$(document).on("click", "#form1", function() {
       
        var count = $('.input_field1').filter(function(input){
            return $(this).val() == "";
        }).length;

        alert(count);
        
    });

HTML

<div id="form1">
 <span>Number of Incomplete Input: 2</span>
 <input type="text" value="" class="input_field1">
 <input type="text" value=""class="input_field1">
</div>

<div id="form2">
 <span>Number of Incomplete Input: 1</span>
 <input type="text" value="Test" class="input_field2">
 <input type="text" value="" class="input_field2">
</div>

Comments

0

See snippet below:

It has commented and if you put some effort on it, you can have a jQuery plugin out of it.

(function () {
  'use strict';
  
  var 
    // this use to prevent event conflict
    namespace = 'customValidation',
    submitResult = true;
    
  var
    input,
    inputType,
    inputParent,
    inputNamePlaceholder,
    //-----
    writableInputTypes = ['text', 'password'],
    checkboxInputType = 'checkbox';
    
  var
    errorContainerCls = 'error-container';
  
  // Add this function in global scope
  // Change form status with this function
  function changeFormStatus(status) {
    submitResult = submitResult && status;
  }
  
  // Check if a radio input in a
  // group is checked
  function isRadioChecked(form, name) {
    if(!form || !name) return true;
    
    var radio = $(form).find('input[type="radio"][name="' + name.toString() + '"]:checked');
    
    return typeof radio !== 'undefined' && radio.length 
      ? true 
      : false;
  }
  
  function eachInputCall(inp, isInSubmit) {
    input = $(inp);
    inputType = input.attr('type');
    // assume that we have a name placeholder in
    // attributes named data-name-placeholder
    inputNamePlaceholder = input.attr('data-name-placeholder');
    // if it is not present,
    // we should have backup placeholder
    inputNamePlaceholder = inputNamePlaceholder ? inputNamePlaceholder : 'input';

    if(!inputType) return;
    // you have three type of inputs in simple form
    // that you can make realtime validation for them
    // 1. writable inputs ✓
    // 2. checkbox inputs ✓
    // 3. radio inputs ✕
    
    // for item 3 you should write
    // another `else if` condition
    // but you should have it for
    // each name (it was easier if it was a plugin)

    // radio inputs is not good for realtime
    // unchecked validation.
    // You can check radios through submit event

    // let make it lowercase
    inputType = inputType.toLowerCase();

    // first check type of input
    if ($.inArray(inputType, writableInputTypes) !== -1) {
       if(!isInSubmit) {
        input.on('input.' + namespace, function () {
          writableInputChange(this);
        });
       } else {
        writableInputChange(inp);
       }
    } else if ('checkbox' == inputType) { // if it is checkbox
      if(!isInSubmit) {
        input.on('change.' + namespace, function () {
          checkboxInputChange(this);
        });
      } else {
        checkboxInputChange(inp);
      }
    }
  }
  
  // Check if an input has some validation
  // (here we have just required or not empty)
  function writableInputChange(inp) {
    // I use $(this) instead of input
    // to prevent conflict if selector
    // is a class for an input

    if('' == $.trim($(inp).val())) {
      changeFormStatus(false);

      // your appropriate message

      // you can use bootstrap's popover
      // to modefy just input element 
      // and make your html structure
      // more flexible

      // or

      // if your inputs are in
      // separate containers do
      // somthing like below
      inputParent = $(inp).parent();
      if(!inputParent.children('.' + errorContainerCls).length) {
        inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please fill ' + inputNamePlaceholder));
      }
    } else {
      changeFormStatus(true);

      // I assume we have separate
      // containers for each input
      inputParent = $(inp).parent();
      inputParent.children('.' + errorContainerCls).remove();
    }
  }
  
  // Check if an checkbox is checked
  function checkboxInputChange(chk) {
    if(!$(chk).is(':checked')) {
      changeFormStatus(false);

      // if your inputs are in
      // separate containers do
      // somthing like below
      inputParent = $(chk).parent();
      if(!inputParent.children('.' + errorContainerCls).length) {
        inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please check ' + inputNamePlaceholder));
      }
    } else {
      changeFormStatus(true);

      // I assume we have separate
      // containers for each input
      inputParent = $(chk).parent();
      inputParent.children('.' + errorContainerCls).remove();
    }
  }
  
  $(function () {
    var 
      form = $('#form'),
      // you can change this selector with your classes
      formInputs = form.find('> .input-group > input');
      
    formInputs.each(function () {
      eachInputCall(this);
    });
    
    form.submit(function () {
      submitResult = true;
      
      // check all inputs after form submission
      formInputs.each(function () {
        eachInputCall(this, true);
      });
    
      // Because of radio grouping by name,
      // we should select them separately
      var selectedGender = isRadioChecked($(this), 'gender');
      var parent;
      if(selectedGender) {
        changeFormStatus(true);
        
        
        parent = $(this).find('input[type="radio"][name="gender"]').parent();
        parent.children('.' + errorContainerCls).remove();
      } else {
        changeFormStatus(false);
        
        // I assume that all radios are in
        // a separate container
        parent = $(this).find('input[type="radio"][name="gender"]').parent();
        if(!parent.children('.' + errorContainerCls).length) {
          parent.append($('<div class="' + errorContainerCls + '" />').text('Please check your gender'));
        }
      }
      
      if(!submitResult) {
        console.log('There are errors during validations!');
      }
      
      return submitResult;
    });
  });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form">
  <div class="input-group">
    <input type="text" name="input1" data-name-placeholder="name">
  </div>
  <div class="input-group">
    <input type="checkbox" name="input2" data-name-placeholder="agreement">
  </div>
  <div class="input-group">
    <input type="radio" name="gender">
    <input type="radio" name="gender">
  </div>
  
  <button type="submit">
    submit
  </button>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.