Theodore Steiner
Theodore Steiner

Reputation: 1615

Validating Dynamically Added Form Inputs - Vanilla JS

I'm building a multipage form. On a few of the form's pages, I have questions that allow the user to add inputs dynamically if they need to add a job, or an award, etcetera. Here's what I'd like to do/what I have done so far.

What I Want to Do:

  1. As the user adds fields dynamically, I want to validate those fields to make sure they have been filled in, and they are not just trying to move to the next page of the form with empty inputs.
  2. After all the fields are successfully validated, a "Next" button at the bottom of the page, which up until this point was disabled, will become reenabled.

What I know How To Do

With some help, I've been able to workout a validation pattern for the inputs that are not dynamically added (such as First Name, Last Name) and I can extend this same logic to the first set of inputs that are not added dynamically. I have also worked out how to re-enable the "Next" button once all fields are good.

What I do Not Know How To Do

How do I write a function that extends the logic of the simple validation test to also check for dynamically added iterations.

http://codepen.io/theodore_steiner/pen/gwKAQX

var i = 0;
function addJob()
{
   
   //if(i <= 1)
   //{
        i++;
      var div = document.createElement("div");
      div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'"> <input type="date" class="three-lines" name="years_'+i+'"> <input type="button" value="-" onclick="removeJob(this)">';
    
    document.getElementById("employmentHistory").appendChild(div);
  //}
}

function removeJob(div)
{
    document.getElementById("employmentHistory").removeChild(div.parentNode);
    i--;
};



function checkPage2()
{
    
    var schoolBoard_1 = document.getElementById("schoolBoard_1").value;
    
    if(!schoolBoard_1.match(/^[a-zA-Z]*$/))
    {
        console.log("something is wrong");
    }
    else
    {
        console.log("Working");
    }
};
  
 <div id="page2-content">
                <div class="input-group" id="previousTeachingExperience">
                    <p class="subtitleDirection">Please list in chronological order, beginning with your most recent, any and all full-time or part-time teaching positions you have held.</p>
                    <div class="clearFix"></div>
                    <label id="teachingExpierience">Teaching Experience *</label>
                    <div id="employmentHistory">
                        <input type="text" class="three-lines" name="schoolBoard_1" id="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='School Board'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
                        <input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
                        <input type="date" class="three-lines" name="years_1" />
                        <input type="button" name="myButton" onclick="addJob()" value="+" />
                    </div>     
                </div><!--end of previousTeachingExperience Div -->

Upvotes: 0

Views: 1414

Answers (2)

Ava
Ava

Reputation: 2429

For every element that you make with document.createElement(...), you can bind to the onchange event of the input element, and then perform your validation.

Here's an updated version of your CodePen.

For example:

HTML

<div id="container">

</div>

Javascript

var container = document.getElementById("container");
var inputElement = document.createElement("input");

inputElement.type = "text";
inputElement.onchange = function(e){
    console.log("Do validation!");
};

container.appendChild(inputElement);

In this case I'm directly creating the input element so I have access to its onchange property, but you can easily also create a wrapping div and append the inputElement to that.

Note: Depending on the freqency in which you want the validation to fire, you could bind to the keyup event instead, which fires every time the user releases a key while typing in the box, IE:

inputElement.addEventListener("keyup", function(e){
    console.log("Do validation!");
});

Upvotes: 0

Pierre Tasci
Pierre Tasci

Reputation: 450

Instead of trying to validate each individual input element, I would recommend trying to validate them all at once. I believe that is what your checkPage2 function is doing.

You can add the onBlur event handler or the onKeyUp event handler you are currently using to all added inputs to run your form wide validation. This has the effect of checking each individual form element if it is valid so you know for sure you can enable the submit button.

Lastly, when removeJob is called, you should also run the form wide validation. It would look something like this:

function addJob()
{
    i++;
    var div = document.createElement("div");
    div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'" onkeyup="checkPage2()"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'" onkeyup="checkPage2()"> <input type="date" class="three-lines" name="years_'+i+'" onkeyup="checkPage2()"> <input type="button" value="-" onclick="removeJob(this)">';

    document.getElementById("employmentHistory").appendChild(div);
}

function removeJob(div)
{
    document.getElementById("employmentHistory").removeChild(div.parentNode);
    i--;
    checkPage2();
};

Upvotes: 1

Related Questions