Home > Back-end >  How to remove a part of the content of a div with jQuery?
How to remove a part of the content of a div with jQuery?

Time:06-29

When I click on a checkbox, I append some content to a div (#item_list)

    if(cb_new.prop('checked')) {
        $("#item_list").append("<input type='hidden' name='post[]' value="  this.value  ">");
        
    } else {            
        // ??           
    }

When I uncheck the box I want that exact same string to be removed from the div. Keeping all the others that have a different value (this.value).

So for example I could have:

<div id="item_list"> 
<input type="hidden" name="post[]" value="102">
<input type="hidden" name="post[]" value="93">
</div>

But if I uncheck

<input type="checkbox" id="d-102-2" name="d-102" value="102" data-id="d-102"> 

I want :

<div id="item_list"> 
<input type="hidden" name="post[]" value="93"> 
</div>

If I check it again, I want it back.

How can I do that?

CodePudding user response:

A vanilla JS solution would look like:

Updated according to your expanded requirements.

document.querySelector(`#item_list input[value='${this.value}']`).remove();

This will query the DOM, find an input element, with a value attribute whose value is equal to this.value, and remove it from the DOM with the remove() method.

A more detailed implementation isn't easy to give without having more information.

CodePudding user response:

You can use the data attribute to assign unique id to the checkbox, once it is checked, input element with same data-uid is added and once unchecked we remove the input element with same data-uid

  $(document).ready(function() {
    $("#cb_new").change(function() {
      if ($(this).prop('checked')) {
        $("#item_list").append($("<input data-uid='" $(this).data('uid') "' type='text' name='post[]' class='newItem' value='"   $(this).val()   "'>"));
      } else {
        $('.newItem[data-uid=' $(this).data('uid') ']').remove();
      }
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="cb_new" data-uid="8080" value="tick Me" name="test"/><label for="test">Tick Me</label>
<div id="item_list" style="border:1px solid tomato">

</div>

  • Related