如何克隆复选框,现在取消选中隐藏该clonedbox并取消选中父项,而取消选中父项则隐藏clonedbox

时间:2018-09-21 13:50:14

标签: javascript jquery html

$('input').on('change', function() {
  var self = $(this);
  if (self.is(':checked')) {
    self.closest('.label-wrap').clone().addClass("clone")
      .appendTo("header");
    self.closest('.label-wrap').find('label').addClass("is-checked");
  } else {
    $('header label[for="' + self.attr('id') + '"]').replaceWith('');
    self.closest('.wrap').find('.clone').hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-6">
    <header></header>
  </div>
  <form class="col-md-6">
    <div class="wrap">
      <div class="label-wrap">
        <label for="one">Checkbox 1</label>
        <input id="one" type="checkbox" />
      </div>
    </div>
    <div class="wrap">
      <div class="label-wrap">
        <label for="two">Checkbox 2</label>
        <input id="two" type="checkbox" />
      </div>
    </div>
    <div class="wrap">
      <div class="label-wrap">
        <label for="three">Checkbox 3</label>
        <input id="three" type="checkbox" />
      </div>
    </div>
  </form>
</div>

在这里我要实现的是在checkbox1上,它必须创建一个clone元素(clonedcheckbox1),在取消选中克隆的checkbox(clonedcheckbox1)时,隐藏该复选框并取消选中父复选框(checkbox1)

   [。] checkbox1 [。] clonedcheckbox1

      [] checkbox2

[。] checkbox3 [。] clonedcheckbox3

1 个答案:

答案 0 :(得分:0)

您可以委派一个更改事件,以便可以随时进行绑定以删除克隆并在取消选中克隆时取消选中原始副本:

$('.checkbox').on('change', function() {
  var $this = $(this);
  var $parent = $this.parent();

  if (this.checked) {
    // if checked clone without events and append
    $parent.after($parent.clone().addClass('clone'));
  } else {
    // otherwise remove clone
    $parent.next('.clone').remove();
  }
});

$('.wrap').on('change', '.clone .checkbox', function() { // delegate your event for dynamically added elements
  // can only be unchecked
  var $this = $(this);
  $this.closest('.wrap').find('.checkbox').prop('checked', false); // use prop to uncheck original
  $this.parent().remove(); // remove clone
});
.wrap {
  display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-6">
    <header></header>
  </div>
  <form class="col-md-6">
    <div class="wrap">
      <div class="label-wrap">
        <label for="one">Checkbox 1</label>
        <input id="one" type="checkbox" class="checkbox" />
      </div>
    </div>
    <div class="wrap">
      <div class="label-wrap">
        <label for="two">Checkbox 2</label>
        <input id="two" type="checkbox" class="checkbox" />
      </div>
    </div>
    <div class="wrap">
      <div class="label-wrap">
        <label for="three">Checkbox 3</label>
        <input id="three" type="checkbox" class="checkbox" />
      </div>
    </div>
  </form>