A Pen by Daniel Hinds-Bond

Thumbnail
This awesome code was written by 007design, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 007design ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>A Pen by  Daniel Hinds-Bond</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <section class="form-section">
  <form id="form_step_one" class="active">
    <input type="text" id="first_name" class="form-field">
    <span class="error" data-error="first_name"></span>
    <button type="submit">Submit</button>
  </form>
  <form id="form_step_two">
    <select id="age" class="form-field">
      <option value="">Please Select</option>
      <option value="old">Old</option>
      <option value="young">Young</option>
    </select>
    <span class="error" data-error="age"></span>
    <button type="submit">Submit</button>
  </form>
</section>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/007design/a-pen-by-daniel-hinds-bond-yjjXeP */
form {
  display: none;
}

form.active {
  display: block;
}

/*Downloaded from https://www.codeseek.co/007design/a-pen-by-daniel-hinds-bond-yjjXeP */
const formRegistry = {step:0,forms:[]}
const forms = document.querySelectorAll('form');

for (var a=0; a<forms.length; a++) {
  const form = forms[a];
  const fields = form.querySelectorAll('.form-field');
  
  form.fields = [];
  
  for (var b=0; b<fields.length; b++) {
    const field = fields[b];
    field.validate = function() {
      document.querySelector('[data-error="'+this.id+'"]').innerHTML = (this.value ? "" : "error");
      return !!this.value;
    };
    
    form.fields.push(field);
  }
    
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    
    let isValid = true;
    for (var b=0; b<form.fields.length; b++) {
      const v = form.fields[b].validate();
      if (!v) {
        isValid = false;
        break;
      }
    }
    
    if (isValid) {
      formRegistry.step = formRegistry.step + 1;
    } else return;
    
    if (formRegistry.step > formRegistry.forms.length) {
      //submit
    } else {
      formRegistry.forms[formRegistry.step-1].classList.remove('active');
      formRegistry.forms[formRegistry.step].classList.add('active');
    }
  });
  
  formRegistry.forms.push(form);
}

Comments