Skip to content Skip to sidebar Skip to footer

Input Type Text Fields Are Repeating After Unchecking The Checkbox

I have check boxes called as Firstname, Lastname and Email. I have to display the input type after clicking on the check box or if unchecked then remove the check box. Also, I am t

Solution 1:

The simplest way to do this would be to give the div elements that you append the id of the checkbox as a class, so that they can be easily identified when you need to remove them.

You can also DRY up the code by providing the type of the input to add as a data attribute on the checkbox which can be read in the change event handler, like this:

$(function() {
  $(".add_input").change(function() {
    if (this.checked) {
      $("#items").append('<div class="' + this.id + '"><input type="' + $(this).data('type') + '" name="input[]" placeholder="' + $(this).next('label').text() + '" /></div>');
    } else {
      $('#items').find('.' + this.id).remove();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="check-fields" class="add_input" id="get_first_name" data-type="text">
<label for="get_first_name">First Name</label>

<input type="checkbox" name="check-fields" class="add_input" id="get_last_name" data-type="text">
<label for="get_last_name">Last Name</label>

<input type="checkbox" name="check-fields" class="add_input" id="get_email" data-type="email">
<label for="get_email">Email</label>

<div id="items"></div>

Post a Comment for "Input Type Text Fields Are Repeating After Unchecking The Checkbox"