0

I have a form with more than 10 input/select options but i wish to show most of this form inputs when 4 of my fields specifically are filled.

I've done some research and found

$('input[type="text"]').each(function(){
  // do my things here...
});

but this has 2 issues:

  1. It doesn't work when i fill inputs
  2. One of my fields is select option and here only tries to get inputs

Code

$(function() {
  // show choices DIV only if all fields are filled.
  $('input[type="text"]').each(function() {
    if ($(this).val() != "") {
      $('.choices').show();
    } else {
      $('.choices').hide();
    }
  });
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />


<form action="" method="POST">
  <div class="row">
    <div class="col-md-3">
      <div class="form-group">
        <div class="sm-form-design">
          <input id="seq_no" type="text" class="form-control" name="seq_no" required>
          <label for="seq_no" class="control-label">Seq No.</label>
        </div>
      </div>
    </div>
    <div class="col-md-9">
      <div class="form-group">
        <div class="sm-form-design">
          <input id="question" type="text" class="form-control" name="question" required>
          <label for="question" class="control-label">Question</label>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-6 sm-form-design">
      <select name="type" id="type" class="form-control">
        <option value="dropdown">Dropdown</option>
        <option value="multiple">Multiple</option>
        <option value="radio">Radio Buttons</option>
        <option value="input">Input</option>
      </select>
      <label for="type" class="control-label">Type</label>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <div class="sm-form-design">
          <input type="text" name="quiz_time" class="form-control" id="masked-input-time" required>
          <label for="quiz_time" class="control-label">Time *</label>
        </div>
      </div>
    </div>
  </div>

  <!-- show this part when all fields above are filled -->
  <div class="row choices">
    <div class="col-md-12">
      <h5>Choices:</h5>
    </div>
  </div>
  </div>

  <button type="submit" class="btn btn-primary">Save</button>
</form>

Question

How can I validate all my first 4 fields before showing rest of the form?

Any idea?

3 Answers 3

3

While Shiladitya's answer works, and is closest to your own code, I find it cleaner to handle forms by serializing data into an object as input occurs. This allows you to more easily reason about validation, as you only have to validate an object, not DOM elements.

Here is a pared down example:

$(function() {
  const formData = {}
  const $form = $('#form-a')
  const $partTwo = $('#part-2')
  
  // some real validation here
  const isValidPartOne = data =>
    data.a && data.b && data.c
  
  const showPartTwo = () => $partTwo.show()

  $form.on('input', ({target}) => {
    formData[target.name] = target.value
    
    // form data is available at all times
    console.log('formData =', formData)

    if (isValidPartOne(formData)) {
      showPartTwo()
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form-a">
  <div id="part-1">
    PART 1
    <input name="a" />
    <input name="b" />
    <select name="c">
      <option value="" disabled selected>Choose One</option>
      <option value="a">A</option>
      <option value="b">B</option>
    </select>
  </div>
  
  <div id="part-2" style="display:none;">
    PART 2
    <input name="d" />
  </div>

</form>

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

4 Comments

thanks, i tried your code here when i remove my inputs from PART 1 part two still remains in screen can we hide it in that situation?
@mafortis yea, if you want to hide it when part1 is no longer valid, you can add that as an else to the if (isValidPartOne(formData)) conditional.
thanks, this is much cleaner however i still have issue with my time input and can't include it to validation
Hey @mafortis were you able to solve the problem you had? Here is a fiddle with the same code (slightly tweaked) matching the HTML you provided: jsfiddle.net/fzhqvo8u . I don't see any problem on a surface level with validating each field. Is there a specific problem you're running into?
2

Here you go with a solution

$(function() {

  $('.choices').hide();

  // show choices DIV only if all fields are filled.
  $('select').change(function() {
    validateInput();
  });
  
  $('input[type="text"]').keyup(function() {
    validateInput();
  });
  
  function validateInput() {
   var valid = true;
    $('input[type="text"], select').each(function() {
      if ($(this).val() === "") {
        valid = false;
      }
    });

    if (valid) {
     $('.choices').show();
    } else {
     $('.choices').hide();
    }
  }
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />


<form action="" method="POST">
  <div class="row">
    <div class="col-md-3">
      <div class="form-group">
        <div class="sm-form-design">
          <input id="seq_no" type="text" class="form-control" name="seq_no" required>
          <label for="seq_no" class="control-label">Seq No.</label>
        </div>
      </div>
    </div>
    <div class="col-md-9">
      <div class="form-group">
        <div class="sm-form-design">
          <input id="question" type="text" class="form-control" name="question" required>
          <label for="question" class="control-label">Question</label>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-6 sm-form-design">
      <select name="type" id="type" class="form-control">
        <option value="dropdown">Dropdown</option>
        <option value="multiple">Multiple</option>
        <option value="radio">Radio Buttons</option>
        <option value="input">Input</option>
      </select>
      <label for="type" class="control-label">Type</label>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <div class="sm-form-design">
          <input type="text" name="quiz_time" class="form-control" id="masked-input-time" required>
          <label for="quiz_time" class="control-label">Time *</label>
        </div>
      </div>
    </div>
  </div>

  <!-- show this part when all fields above are filled -->
  <div class="row choices">
    <div class="col-md-12">
      <h5>Choices:</h5>
    </div>
  </div>
  </div>

  <button type="submit" class="btn btn-primary">Save</button>
</form>

OnChange of any input, please iterate through all the inputs just to check whether each input is empty or has value.

Here you go with a solution for your problem 1 that you mentioned in the comment box

$(function() {

  $('.choices').hide();

  // show choices DIV only if all fields are filled.
  $('select').change(function() {
    validateInput();
  });

  $('input[type="text"]').keyup(function() {
    validateInput();
  });

  // --- Whenever you make an action you can call this method to validate your inputs ----
  function validateInput() {
    var valid = true;
    $('input[type="text"], select').each(function() {
      if ($(this).val() === "") {
        valid = false;
      }
    });

    if (valid) {
      $('.choices').show();
    } else {
      $('.choices').hide();
    }
  }
});

16 Comments

'input[type="text"]' Doesn't this still only check the text type inputs and not the select type input?
Thanks but it has 2 minor bugs. 1 when i fill inputs or clear them it requires clicking outside of the field in order to change status of valid variable and show or hide choices div 2 as soon as I open dropdown (not selected any option yet) it changes status of valid variable.
For the problem 1 is will provide a reusable code which will help you to solve
@Shiladitya not yet bro, still same behavior as before (requires click outside of fields)
@mafortis When you click outside of the field just call that validateInput method
|
0

I am not in a place to properly test but looking at your function I would make the following changes,

$(function() {
  // show choices DIV only if all fields are filled.
  var flag = false
  $('input[type="text"]').each(function() {
    if ($(this).val() != "") {
      flag = true
    } else {
      flag = false
    }
  });
  if (flag) {
     $('.choices').show();
  } else {
     $('.choices').hide();
  }
});
$('input[type="text"]').keyup(function() {
  // call function
});
$('input[type="text"]').keydown(function() {
  // call function
});

2 Comments

sorry i'm confused a bit, we have each as well as keyup and keydown properties, why is that?
.each simply iterates over items in an array and will not listen for when inputs have changes, using the combination of keyup and keydown to call the function will ensure that when users are typing or using the delete key the function will also get called and calculate whether the other inputs should be shown

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.