Lord Rixuel
Lord Rixuel

Reputation: 1243

How to add jQuery validation to cloned sections?

In the original form section, the validation works fine, but the cloned form section doesn't have the validation.

When the original section has an error message, adding will give a new cloned form section but with a duplicated error message.

Making a cloned form section must not show up any error messages and it should validates its own fields only.

So how to add jQuery validation separately to cloned sections?

/*
	jQuery validation: https://jqueryvalidation.org/
*/
$("#aform").validate({
  rules: {
    fullname: {
      required: true
    }
  },
  messages: {
    fullname: {
      required: "Please enter your Full Name."
    }
  }
});

function addval2() {
  $("#aform").validate({
    rules: {
      fullname_2: {
        required: true
      }
    },
    messages: {
      fullname_2: {
        required: "Please enter your Full Name.2"
      }
    }
  });
}

/*
	Code for cloning form section.
	Plugin repo: https://github.com/tristandenyer/Clone-section-of-form-using-jQuery
*/
$(function() {
  $('#btnAdd').click(function() {
    var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
      newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
      newElem = $('#entry' + num).clone(false).attr('id', 'entry' + newNum).hide().fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value

    // New attributes (id, class, name) for cloned inputs			
    newElem.find('.fullname')
      .attr('id', 'fullname_' + newNum)
      .attr('class', 'fullname_' + newNum)
      .attr('name', 'fullname_' + newNum).val('');

    newElem.find('.error').remove();

    // Add validation for cloned sections.
    addval2();

    // Insert the new element after the last "duplicatable" input field
    $('#entry' + num).after(newElem);

    // Enable the "remove" button. This only shows once you have a duplicated section.
    $('#btnDel').attr("style", "visibility: true");

    // Max form sections, including the original.
    if (newNum == 2)
      $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit"); // value here updates the text in the 'add' button when the limit is reached  
  });

  $('#btnDel').click(function() {
    var num = $('.clonedInput').length;
    // how many "duplicatable" input fields we currently have
    $('#entry' + num).slideUp('slow', function() {
      $(this).remove();
      // if only one element remains, disable the "remove" button
      if (num - 1 === 1)
        $('#btnDel').attr("style", "visibility: hidden");
      // enable the "add" button
      $('#btnAdd').attr('disabled', false).prop('value', "add section");
    });
    return false; // Removes the last section you added
  });

  // Enable the "add" button
  $('#btnAdd').attr('disabled', false);
  // Disable the "remove" button
  $('#btnDel').attr("style", "visibility: hidden");
});
<h1>jQuery validation and cloning form sections</h1>	

<div id="entry1" class="clonedInput">
  <h2>Form</h2>
  <form id="aform" class="aform" name="aform" method="get">
    <div>
      <label for="fullname">Full Name</label>
      <input id="fullname" class="fullname" name="fullname" minlength="2" required>
    </div>
  </form>
</div>

<p>
  <button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
  <button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>

Upvotes: 1

Views: 1943

Answers (1)

Vladimir Salguero
Vladimir Salguero

Reputation: 5947

Probably the problem is that you create a second form with the id = "aform" and remember that an id should not be repeated, you can place the div id = "entry1" class = "clonedInput" inside the form so that the two fields created are inside Of a single form.

Try this

<h1>jQuery validation and cloning form sections</h1>    
<form id="aform" class="aform" name="aform" method="get">

<div id="entry1" class="clonedInput">   
<h2>Form</h2>
      <label for="fullname">Full Name</label>
      <input id="fullname" class="fullname" name="fullname" minlength="2" required>
 </div>
</form>
<p>
<button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
<button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>

<script>

$("#aform").validate({
rules: {
fullname: {
  required: true
}
},
messages: {
fullname: {
  required: "Please enter your Full Name."
}
}
});

/*
Code for cloning form section.
Plugin repo: https://github.com/tristandenyer/Clone-section-of-form-using-jQuery
*/
$(function() {
  $('#btnAdd').click(function() {
    var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
    newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
    newElem = $('#entry' + num).clone(false).attr('id', 'entry' + newNum).hide().fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value

   // New attributes (id, class, name) for cloned inputs            
   newElem.find('.fullname')
  .attr('id', 'fullname_' + newNum)
  .attr('class', 'fullname_' + newNum)
  .attr('name', 'fullname_' + newNum).val('');

   newElem.find('.error').remove();


// Insert the new element after the last "duplicatable" input field
$('#entry' + num).after(newElem);

// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel').attr("style", "visibility: true");

// Max form sections, including the original.
if (newNum == 2)
     $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit"); // value here updates the text in the 'add' button when the limit is reached  
 });

 $('#btnDel').click(function() {
    var num = $('.clonedInput').length;
    // how many "duplicatable" input fields we currently have
    $('#entry' + num).slideUp('slow', function() {
      $(this).remove();
      // if only one element remains, disable the "remove" button
     if (num - 1 === 1)
       $('#btnDel').attr("style", "visibility: hidden");
      // enable the "add" button
      $('#btnAdd').attr('disabled', false).prop('value', "add section");
    });
    return false; // Removes the last section you added
  });

 // Enable the "add" button
 $('#btnAdd').attr('disabled', false);
 // Disable the "remove" button
 $('#btnDel').attr("style", "visibility: hidden");
});

</script>

Upvotes: 1

Related Questions