Remove Sibling is removing extra elements in jquery

117 views Asked by At

This is one of the piece of my html

<label class="checkbox" data-appid="1" data-moduleid="1" data-permissionid="128" data-processid="1" data-screenid="1">
  <input type="checkbox" name="screen_permission_id[128]" value="128" checked="checked">
  <span></span>
  Add
here is my jquery code
$(document).on('change', 'input:checkbox', function() {
   console.log($(this))
    if ($(this).is(':checked') == false) {
        $(this).siblings($('input[type=hidden]')).remove()
    } else {
        let tr = $(this).closest('label');

        let appid = tr.attr("data-appid")
        let moduleid = tr.attr("data-moduleid")
        let permissionid = tr.attr("data-permissionid")
        let processid = tr.attr("data-processid")
        let screenid = tr.attr("data-screenid")

        $(this).closest('label').append('<input type="hidden" name="app_module_id[' + permissionid + ']" value="' + moduleid + '"> <input type="hidden" name="module_process_id[' + permissionid + ']" value="' + processid + '"><input type="hidden" name="process_screen_id[' + permissionid + ']" value="' + screenid + '">')
    }



})

When i uncheck the checkbox. Alongwith hidden inputs it also deletes my span variable. How i can avoid this situation.

1

There are 1 answers

0
SEYED BABAK ASHRAFI On BEST ANSWER

You can use not in selecting sibling as said in jquery doc.

$(this).siblings($('input[type=hidden]')).not("span").remove()

$(document).on('change', 'input:checkbox', function() {
    if ($(this).prop('checked') == false) {
        $(this).siblings($('input[type=hidden]')).not("span").remove()
        console.clear();
    } else {
        let tr = $(this).closest('label');

        let appid = tr.attr("data-appid")
        let moduleid = tr.attr("data-moduleid")
        let permissionid = tr.attr("data-permissionid")
        let processid = tr.attr("data-processid")
        let screenid = tr.attr("data-screenid")

        $(this).closest('label').append('<input type="hidden" name="app_module_id[' + permissionid + ']" value="' + moduleid + '"> <input type="hidden" name="module_process_id[' + permissionid + ']" value="' + processid + '"><input type="hidden" name="process_screen_id[' + permissionid + ']" value="' + screenid + '">')
        console.log('<input type="hidden" name="app_module_id[' + permissionid + ']" value="' + moduleid + '"> <input type="hidden" name="module_process_id[' + permissionid + ']" value="' + processid + '"><input type="hidden" name="process_screen_id[' + permissionid + ']" value="' + screenid + '">')
    }



})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="checkbox" data-appid="1" data-moduleid="1" data-permissionid="128" data-processid="1" data-screenid="1">
      <input type="checkbox" name="screen_permission_id[128]" value="128" checked="checked">
      <span>Add</span>