javascript - 复选框未绑定(bind)到它们在 DOM jquery 上创建的标签

标签 javascript jquery html dom checkbox

我创建了一个带有复选框的模式,当选中这些复选框时,这些复选框将添加到 DOM 中。我几天来一直在尝试解决的问题是,无论复选框是否选中,标签都会添加到 DOM,而不仅仅是在选中时添加。

当关联的复选框未选中时,我也无法弄清楚如何从 DOM 中删除标签。我可以检查的复选框数量最多为 6 个,这就是我想要的,但是有没有办法最大程度地增加父 div 中子 div 的数量?这样一来,还有另一种安全措施可以依靠,以便一次不能选择超过 6 个标签?

这是一个jsfiddle http://jsfiddle.net/co5w7c9j/就我所掌握的情况而言,希望我解释得足够多,而不会让人听起来太困惑。

下面是我迄今为止编写的 jquery,我认为我在某个地方缺少一个步骤来实现我正在寻找的东西。

感谢您花时间查看我的代码。

// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
    $newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
    $(this).attr('value');
    $('.Specialties').append($newTag);

    /*  if ($('.Specialties > .specTag').has(('[name=specialty]:checked').attr('value'))) {
        $('.Specialties > .specTag').has((this).txt()).remove();  
        } */

    // Count number of checkboxes selected and display in modal
    var increment = 0;
    $('[name=specialty]:checked').each(function() {
        if (this.checked) {
            increment++;
        } else {
            increment--;
        }
        $('#specCount').html(increment);
    });

    // Disable checkboxes when 6 (maximum) are selected
    $("input[type=checkbox][name=specialty]").click(function() {
        var bol = $("input[type=checkbox][name=specialty]:checked").length >= 6;
        $("input[type=checkbox][name=specialty]").not(":checked").attr("disabled", bol);
    });

    // Create array of checked items - add on checked - remove on uncheck
    specialtyArray = $('[name=specialty]:checked').map(function() {
        return $(this).val();

        // if item is in the array, then remove it from the DOM
        if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {}
    });
    console.log(specialtyArray.get());

});

// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
    $('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
    $('#specCount').html(0);
})

// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
    $(this).parent().fadeOut('slow');
    $(this).parent().remove();
});

最佳答案

尝试

// When specilaty is checked, add tag to profile page
$('input[name=specialty]').change(function() {
  var value = this.value;

  //if checked add a new item else remove item.
  if (this.checked) {
    var $newTag = $("<div class='specTag'>" + value + "<div class='xOut'>x</div></div>").attr('data-id', value);
    $('.Specialties').append($newTag);
  } else {
    //use the attribute value which is the same as the input value to find out the item to be removed
    $('.Specialties').find('div.specTag[data-id="' + value + '"]').remove()
  }

  //cache the result since it is used multiple times
  var $checked = $('input[name=specialty]:checked');

  // Count number of checkboxes selected and display in modal
  var increment = $checked.length;
  $('#specCount').html(increment);

  // Disable checkboxes when 6 (maximum) are selected
  var bol = increment.length >= 6;
  //use prop instead of attr to set the disabled state
  $("input[type=checkbox][name=specialty]").not(":checked").prop("disabled", bol);

  // Create array of checked items - add on checked - remove on uncheck
  var specialtyArray = $checked.map(function() {
    return $(this).val();
  });
  console.log(specialtyArray.get());

});

// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
  $('.modal-body > #updateSpecForm > .columns').children().prop('checked', false);
  $('#specCount').html(0);
})

// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
  $(this).parent().fadeOut('slow', function() {
    $(this).remove();
  });
  //uncheck the corresponding checkbox
  $('input[name=specialty][value="' + $(this).closest('.specTag').attr('data-id') + '"]').prop('checked', false)
});
.Specialties {
  background-color: #FFFFFF;
  width: 350px;
  height: 135px;
  margin-left: 249px;
  margin-top: 125px;
  top: 0;
  position: absolute;
  z-index: 1;
}
.specTag {
  background-color: #51b848;
  color: #FFFFFF;
  font-weight: 200;
  letter-spacing: 1px;
  font-size: 12px;
  width: 150px;
  height 30px;
  padding: 8px;
  position: relative;
  margin-left: 10px;
  margin-bottom: 5px;
  border-radius: 5px;
  display: inline-block;
}
.xOut {
  background-color: #FFFFFF;
  width: 25px;
  padding: 3px;
  position: absolute;
  right: 5px;
  text-align: center;
  color: #333333;
  top: 5px;
  border-radius: 0 3px 3px 0;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="GET" id="updateSpecForm">
  <!-- ATHLETIC TRAINER OPTIONS -->
  <div class="columns" id="athleticTrainer">
    <input type="checkbox" name="specialty" value="Boot Camp" />Boot Camp
    <br />
    <input type="checkbox" name="specialty" value="Children's Fitness" />Children's Fitness
    <br />
    <input type="checkbox" name="specialty" value="Circuit Training" />Circuit Training
    <br />
    <input type="checkbox" name="specialty" value="Core Training" />Core Training
    <br />
    <input type="checkbox" name="specialty" value="Cycling/Spinning" />Cycling/Spinning
    <br />
    <input type="checkbox" name="specialty" value="Dance" />Dance
    <br />
    <input type="checkbox" name="specialty" value="Flexibility/Balance" />Flexibility/Balance
    <br />
    <input type="checkbox" name="specialty" value="Meal Planning" />Meal Planning
    <br />
    <input type="checkbox" name="specialty" value="Men's Fitness" />Men's Fitness
    <br />
    <input type="checkbox" name="specialty" value="Women's Fitness" />Women's Fitness
    <br />
  </div>
  <div class="Specialties">
    <!-- SHOW BELOW DIV ONLY IF LOGGED IN -->
    <!-- <div class="updateOn"><a href="#updateSpecialties" class="updateSpecialties" role="button" data-toggle="modal">+ Update My Specialties</a></div> -->
    <!-- ***PRO CAN ADD UP TO 6 SPECIALY TAGS*** -->
  </div>
</form>

关于javascript - 复选框未绑定(bind)到它们在 DOM jquery 上创建的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714484/

相关文章:

javascript - 在 JavaScript 中实现具有容差的二分搜索?

javascript - 使用 jQuery 在 Mousehoever 和 mouseout 上调用 javascript 函数

javascript - 以最大宽度在 div 中居中图像

jquery - 移动/字形图标和字体大小调整上的 Bootstrap 选项卡

html - 在 Bootstrap 中,如何控制徽章的高度?

javascript - (已关闭)未捕获的类型错误 : Cannot call method 'download' of undefined

javascript - js html背景颜色与高亮

html - 需要使用 twitter/bootstrap 更正这个复杂的网格/表格布局

html - 如何为 HTML 创建自定义标签

javascript - 具有默认值的屏蔽输入插件