Michael Barley Michael Barley - 5 months ago 33
jQuery Question

Add/remove form element depending on if checkbox is checked

I have created a script which creates adds a form element when a check-box is checked. However, when i un check the check-box and then check it again. A new element is created as well as leaving the old one.

I would like, when the check-box is unchecked, the element which was created is removed. When it is checked, the element is added.

// This script checks to see if a tick-box has been ticked
// If so, displays more form options
$(function() {
$('#contactform :checkbox').click(function() {
var $this = $(this);
if ($this.is(':checked')) {

var newInput = $('<div class="col-lg-12 col-pad7"><div class="form-group"><label class="sr-only" for="name">Name<br></label><input type="text" name="name" id="name" value="" class="form-control newInput required" placeholder="Name" data-name="Name"></div></div>');

$('input#checkbox').after(newInput);

} else {
newInput.remove();
}
});
});

Answer

$('#contactform :checkbox').change(function() {
  var $this = $(this);
  if ($this.is(':checked')) {

    var newInput = $('<div id="addme" class="col-lg-12 col-pad7"><div class="form-group"><label class="sr-only" for="name">Name<br></label><input type="text" name="name" id="name" value="" class="form-control newInput required" placeholder="Name" data-name="Name"></div></div>');

    $('#contactform').append(newInput);

  } else {
    $('#contactform').find('#addme').remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='contactform'>

  <input type='checkbox'>
</div>

  1. Use change event
  2. Put an ID to the element you append. On uncheck find the ID then remove.
Comments