无法完全删除输入复选框

时间:2019-07-18 15:04:07

标签: javascript jquery thymeleaf

这是div

    <div id="current-menus-for-role-div">
    <h2>current for role</h2>
    <div class="list-group" id="current-menus-for-role-checkboxes">
        <!--        <input type="checkbox" /> Some label<br />-->
        <!--        <input type="checkbox" /> Some other label<br />-->
    </div>

    <button type="submit" id="remove-menus-from-role-btn" class="btn btn-success">Sil</button>
</div>

我在此添加复选框:

   var currentMenusForRoleCheckboxes = $('#current-menus-for-role-checkboxes');
         currentMenusForRoleCheckboxes.append('<input type="checkbox" id="'
                    + menu.id +
                    '"/> ' + menu.item + '<br />');

单击按钮时,我要删除一个接一个地选中的复选框:

        $('#remove-menus-from-role-btn').click(

            function (event) {
                event.preventDefault();

                function fireRemoveMenusFromRole() {

                    $('div#current-menus-for-role-div input[type=checkbox]')
                        .each(function () {
                            if ($(this).is(":checked") && !menuIdsToBeDeleted.includes(this.id)) {
                                console.log("selectedmenutoremove: " + this + " id:" + this.id);
                                menuIdsToBeDeleted.push(this.id);
                                console.log(" to menuIdsToBeDeleted added: " + menuIdsToBeDeleted);
debugger
                                $(this).remove();
                            }

                        });
                }

                fireRemoveMenusFromRole();
            });

但是

     $(this).remove();

这只会删除复选框图标。标签留在那里:(

我尝试了父删除,并且

             $(this).closest("list-group").remove();

但无法删除

2 个答案:

答案 0 :(得分:0)

使用适当的<label>标签包裹<input>并包裹在<div>这样的块元素中,而不要使用<br>,然后删除复选框父项<div> < / p>

<div class="list-group" id="current-menus-for-role-checkboxes">
       <div><label><input type="checkbox" /> Some label</label></div>
       <div><label><input type="checkbox" /> Some other label</label></div>
</div>

JS

$(this).closest('div').remove();

答案 1 :(得分:0)

尝试一下:

$('input:checkbox').on('change', function(){
  $(this).nextUntil('input:checkbox').remove(); // remove every tag until the next checkbox
  $(this)[0].nextSibling.remove(); // remove the text next to the checkbox
  $(this).remove(); // remove the element itself
});

示例:https://jsfiddle.net/4kgqhn8f/