0

i'm using jQuery append function to clone the input fields on front-end, it is working fine but the issue is i have validation on parent element, it is not working on the newly append input fields. This is my jQuery code.

jQuery(function($) {
  $("#addChild").click(function() {
    $(".name-field:first").clone().find("input").val("").end()
      .removeAttr("id")
      .appendTo("#additionalselects")
      .append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
  });
  $("body").on('click', ".delete", function() {
    $(this).closest(".name-field").remove();
  });
});
//Validation
$(document).ready(function() {

  $('.name-field').on('input', function() {
    // added for bit of simplicity or you can directly get valuess
    var name = $('input[name="firstname"]').val();
    var date = $('input[name="date"]').val();
    if (name != "" && date != "") {
      // values seems filled remove class  
      $('#stepname').removeClass('disabled');
    } else {
      // user has emptied some input so add class again.
      $('#stepname').addClass('disabled');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="name-field" class="name-field row">
  <div class="col-xs-12 col-sm-6 childname">
    <div class="field text-left">
      <label class="text-left">Name of child</label>
      <input id="firstname" class="firstname" name="firstname" type="text" />
    </div>
  </div>
  <div class="col-xs-12 col-sm-6 dateofbirth">
    <div class="field text-left">
      <label class="text-left">Date of birth</label>
      <input type="text" class="date" id="thedate" name="date" />
    </div>
  </div>
</div>

<a href="#" id="stepname" class="btn">Next Step</a>

Can anyone help me with this, how can achieve this?

Thanks in advance.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Zain
  • 662
  • 9
  • 26

1 Answers1

0

As you are adding .name-field dynamically so event are not binding to the new rows try to change your parent element like,

$('#additionalselects').on('input','.name-field input',function(){
//^^^ use other static element or document if not works
    var parent = $(this).closest('.name-field'); // get the parent of focused input
    var name = parent.find('input[name="firstname"]').val();
    var date = parent.find('input[name="date"]').val();
    $('#stepname').toggleClass('disabled',(!name || !date));
});

Also you should make the below changes in your HTML,

  1. Remove all id which are part of cloning
  2. Make an array of fields which are to be cloned like firstname[]
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • I did all the changes, when there is only parent element it is not removing the disabled class. – Zain Mar 22 '18 at 08:43
  • I think this code looking only in #additionalselects, ignoring the parent. – Zain Mar 22 '18 at 08:58