11

I have some form fields that are dynamically generated form the database. There are inputs, checkboxes, radio buttons, textarea's, and select's. All the fields are in a parent div with ID dynamic-form-fields. Some fields have a required attribute.

This is a multi-step form so each "step/page" needs to be validated before going on to the next step. So it's not submitting the form.

How can I check if all the required fields in div dynamic-form-fields are filled?

Here's something what my HTML code looks like:

<input type="text" name="dff[]" placeholder="Name" required>
<input type="text" name="dff[]" placeholder="Date of Birth">
<input type="text" name="dff[]" placeholder="Email" required>
<input type="radio" name="gender" value="Male" required>
<input type="radio" name="gender" value="Female" required>
<select name="pet">
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="bird">Bird</option>
</select>

<button id="check">Check</button>

<script>
    document.getElementById("check").onclick = function () {
        if() {
            alert('error please fill all fields!');
        }
    };
</script>

As you see, some fields are required and some are not. It is different every time so the solution has to be dynamic. There are also different types of input's such as select, radio, checkbox, text, etc... How can I make sure every "required" field inside the div ID dynamic-form-fields is filled?


What i've tried:

Maybe something like this but how do I get every type of input (text, radio, checkbox, select, etc...) under the div ID dynamic-form-fields?

$('#dynamic-form-fields input:required').each(function() {
  if ($(this).val() === '')
      alert('error please fill all fields!');
});
pixie123
  • 929
  • 3
  • 14
  • 27
  • You're adding these in div or is it coming wrapped with div from database ? – Code Maniac Jul 18 '19 at 04:37
  • @CodeManiac Hi i saw your answer, I updated the question. It's a multi-step form so your previous wouldn't work since i'm not actually submitting the form. It's a `foreach` loop inside the div `dynamic-form-fields`. – pixie123 Jul 18 '19 at 04:38
  • Why not simply `
    `?
    – Andreas Jul 18 '19 at 04:40
  • if it's a multi-step form what you should actually do is check for values only upto a step instead of all the values, and while submitting you should check all the values, – Code Maniac Jul 18 '19 at 04:44

4 Answers4

24

document.getElementById("check").onclick = function() {
  let allAreFilled = true;
  document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
    if (!allAreFilled) return;
    if (i.type === "radio") {
      let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
        if (r.checked) radioValueCheck = true;
      })
      allAreFilled = radioValueCheck;
      return;
    }
    if (!i.value) { allAreFilled = false;  return; }
  })
  if (!allAreFilled) {
    alert('Fill all the fields');
  }
};
<div id="myForm">
  <input type="text" name="dff[]" placeholder="Name" required>
  <input type="text" name="dff[]" placeholder="Date of Birth">
  <input type="text" name="dff[]" placeholder="Email" required>
  <input type="radio" name="gender" value="Male" required>
  <input type="radio" name="gender" value="Female" required>
  <select name="pet" required>
    <option value="">Select a pet</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="bird">Bird</option>
  </select>
</div>
<button id="check">Check</button>
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
  • But there is a problem, `select` does not work and also `radio` does not work – pixie123 Jul 18 '19 at 04:55
  • I've fixed for select box will work on radio and update here @pixie123 for select you need to have a default unselected one with no value at all to get it to work – Black Mamba Jul 18 '19 at 04:59
  • Okay thank you! but the problem is I don't even have `value`. How can i make it work if its like this: `` – pixie123 Jul 18 '19 at 05:02
  • I've fixed it for radio as well please check. Let me know if any other problem arises – Black Mamba Jul 18 '19 at 05:11
  • The radio does not seem like its working: https://jsfiddle.net/n6b1oxrv/ and also `select` with option without value does not work: https://jsfiddle.net/n6b1oxrv/1/ – pixie123 Jul 18 '19 at 05:36
  • 1
    See this fiddle I think I forgot to update my answer https://jsfiddle.net/02hoa3d7/ I've updated my answer as well sorry for that – Black Mamba Jul 18 '19 at 06:11
  • No problem, that works thank you. But what about if select default option is ` – pixie123 Jul 18 '19 at 06:18
  • 1
    Use disabled on select and not on option – Black Mamba Jul 18 '19 at 06:23
  • There's a _"Tidy"_ button in the snippet editor. Please use it. – Andreas Jul 18 '19 at 09:00
  • Done @Andreas thanks for your suggestion I was using vscode for formatting – Black Mamba Jul 18 '19 at 09:13
  • 1
    Really great answer, Thankx @BlackMamba – SayAz Mar 28 '20 at 19:37
  • 1
    Life saver ty !! – thedude12 Nov 04 '21 at 18:55
  • It also wont work if you place the radios first. You need to change this: "allAreFilled = radioValueCheck;" to this "if (!radioValueCheck ) allAreFilled = false;" – rockstardev Apr 12 '22 at 01:32
  • @coderama fixed can you please have a look, else can you please update the answer yourself I'll review it. – Black Mamba Apr 12 '22 at 05:00
  • 1
    I ended up writing a much longer function that also supports select tags. But your change seems right for the checkbox scenario. Thanks for the radio bit. Saved me some time! – rockstardev Apr 13 '22 at 07:13
11

You can use :invalid to do this.

Demo:

$('#check').on("click", function(){
  let valid = true;
  $('[required]').each(function() {
    if ($(this).is(':invalid') || !$(this).val()) valid = false;
  })
  if (!valid) alert("error please fill all fields!");
  else alert('valid');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="dff[]" placeholder="Name" required>
<input type="text" name="dff[]" placeholder="Date of Birth">
<input type="text" name="dff[]" placeholder="Email" required>
<input type="radio" name="gender" value="Male" required>
<input type="radio" name="gender" value="Female" required>
<select name="pet" required>
    <option selected disabled>Select a pet</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="bird">Bird</option>
</select>

<button id="check">Check</button>
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
  • Can you give a example? – Cuong Le Ngoc Jul 18 '19 at 05:02
  • 1
    Editted my answer. Please check. – Cuong Le Ngoc Jul 18 '19 at 05:57
  • Upvoted. Checking for ":invalid" attribute is simple and great solution. I used ":valid" attribute instead. For email validation, I defined the input type="email" and let browser validate if the entered value is email or not. Later, used this in form validation `validForm = $("#email").is(':valid');` – Sachin G Jun 18 '21 at 20:13
2

You could keep separate checks based on input type, consider the following:

var isEmpty = false;
$("#check").on('click', function() {
  isEmpty = false
  $('input[type=text]:required').each(function() {
    if ($(this).val() === '')
      isEmpty = true;
  });
  var radioSelected = false;
  //$('input[name=gender]:required').each(function() {
  $('input[type=radio]:required').each(function() {
    if ($(this).is(':checked'))
      radioSelected = true;
  });

  if (!radioSelected)
    isEmpty = true;

  if ($("[name=pet]").val() == "")
    isEmpty = true;

  //if (!$(".cb").is(":checked"))
  //  isEmpty = true;

  if (isEmpty)
    alert('error please fill all fields!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="dff[]" placeholder="Name" required>
<input type="text" name="dff[]" placeholder="Date of Birth">
<input type="text" name="dff[]" placeholder="Email" required>
<input type="radio" name="gender" value="Male" required>
<input type="radio" name="gender" value="Female" required>
<select name="pet" required>
  <option value="dog">Dog</option>
  <option value="cat">Cat</option>
  <option value="bird">Bird</option>
</select>
<!--<input type="checkbox" class="cb" required />-->
<button id="check">Check</button>
shrys
  • 5,860
  • 2
  • 21
  • 36
1

You can check is required attribute available or not as,

$('#dynamic-form-fields').each(function() {
    var hasRequired = $(this).attr('required');
    if (typeof hasRequired !== "undefined" && hasRequired !== false) {
        // This is required inputs.
    }
}

Ref : Link

Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39