Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
How to remove a part of the content of a div with jQuery?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!