Michael Barley
Michael Barley

Reputation: 179

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();
  }
  });
});

Upvotes: 2

Views: 2447

Answers (2)

Jai
Jai

Reputation: 74738

You have to check if a div is placed after the check box:

   if ($this.is(':checked') && $this.siblings('div').length === 0) {
         // place the div here

   } else {
       $this.next().remove();// or just place this line
   }

Upvotes: 0

guradio
guradio

Reputation: 15555

$('#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.

Upvotes: 3

Related Questions