Dynamically Add/Remove Input Fields

by Dhruvang Gajjar

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<form id="hello"> 


<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div>
    <input type="text" name="mytext[]" placeholder="X">
    <input type="text" name="mytext1[]" placeholder="Y">
  </div>
</div>
<button>Submit</button>
</form>

JavaScript

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      $(wrapper).append('<div><input type="text" name="mytext[]" placeholder="X"/><input type="text" name="mytext1[]" placeholder="Y" /><a href="#" class="remove_field">Remove</a></div>'); 
      //add input box
      
      $("#hello").validate({
  	ignore: '',
    rules: {
    	'mytext[]': "required",
      'mytext1[]': "required"
    }
  })
      
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
  
  $("#hello").validate({
  	ignore: '',
    rules: {
    	'mytext[]': "required",
      'mytext1[]': "required"
    }
  })
  
});