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();
    }
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox"name="check-fields"class="add_input"id="get_first_name"data-type="text"><labelfor="get_first_name">First Name</label><inputtype="checkbox"name="check-fields"class="add_input"id="get_last_name"data-type="text"><labelfor="get_last_name">Last Name</label><inputtype="checkbox"name="check-fields"class="add_input"id="get_email"data-type="email"><labelfor="get_email">Email</label><divid="items"></div>

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