Check if all required fields are filled in a specific div
Asked Answered
O

4

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!');
});
Overcompensation answered 18/7, 2019 at 4:29 Comment(4)
You're adding these in div or is it coming wrapped with div from database ?Intermediate
@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.Overcompensation
Why not simply <form validate>?Buskined
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,Intermediate
D
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>
Dismuke answered 18/7, 2019 at 4:38 Comment(15)
But there is a problem, select does not work and also radio does not workOvercompensation
I've fixed for select box will work on radio and update here @Overcompensation for select you need to have a default unselected one with no value at all to get it to workDismuke
Okay thank you! but the problem is I don't even have value. How can i make it work if its like this: <option selected disabled>Select a pet</option>Overcompensation
I've fixed it for radio as well please check. Let me know if any other problem arisesDismuke
The radio does not seem like its working: jsfiddle.net/n6b1oxrv and also select with option without value does not work: jsfiddle.net/n6b1oxrv/1Overcompensation
See this fiddle I think I forgot to update my answer jsfiddle.net/02hoa3d7 I've updated my answer as well sorry for thatDismuke
No problem, that works thank you. But what about if select default option is <option selected disabled> and is required? See this: jsfiddle.net/b9Lfyc6h should throw error since select needs to be selected.Overcompensation
Use disabled on select and not on optionDismuke
There's a "Tidy" button in the snippet editor. Please use it.Buskined
Done @Buskined thanks for your suggestion I was using vscode for formattingDismuke
Really great answer, Thankx @BlackMambaLanguid
Life saver ty !!Bowfin
It also wont work if you place the radios first. You need to change this: "allAreFilled = radioValueCheck;" to this "if (!radioValueCheck ) allAreFilled = false;"Phonology
@coderama fixed can you please have a look, else can you please update the answer yourself I'll review it.Dismuke
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!Phonology
F
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>
Fults answered 18/7, 2019 at 4:48 Comment(3)
Can you give a example?Fults
Editted my answer. Please check.Fults
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');Prosthodontist
D
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>
Deen answered 18/7, 2019 at 4:42 Comment(2)
@Overcompensation glad it helpedDeen
sorry but select and checkbox does not work when added and requiredOvercompensation
R
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

Ration answered 18/7, 2019 at 4:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.