Matthew Bram
Matthew Bram

Reputation: 13

jQuery - Looping over all elements and removing those with a specific attribute

I'm new to jQuery and am still learning the syntax. I need help looping over all of the checkboxes in a specific form and remove those elements that I set with a "value" of x from the server. The syntax I have so far, which is not working is:

$('#FormA > :checkbox').each(function() {
     var i = $(this);
     if(i.attr('value') == "-99")
     {
          i.remove();   
     }
});

It looks after reading the API that under the hood the .each() method does a "java enhanced for loop" style iteration on all of the DOM elements that I pass into jQuery. Not sure though...

Thanks for your help!

Upvotes: 1

Views: 1058

Answers (6)

ChrisGP
ChrisGP

Reputation: 437

use this:

$('.YourClass:checked').each(function(){
i=$(this)
if(i.val()=='-99'){i.remove()}
})

Upvotes: -1

Loktar
Loktar

Reputation: 35309

Look Ma no jQuery! Little late to the party, but a pure JS way.

var form = document.getElementById("formA");

[].forEach.call(form.querySelectorAll('input[type="checkbox"][value="-99"]'),function(el){form.removeChild(el);});​

Live Demo

Also its MAGNITUDES faster.

JS Perf

Upvotes: 1

James Allardice
James Allardice

Reputation: 165951

Most jQuery methods are applied to every element in the matched set. To do what you are trying to do, you just need to select the right set of elements and call remove. There's no need for the each. For example:

$("#FormA > :checkbox[value='-99']").remove();

This uses an "attribute equals" selector to find checkbox input elements with a value of -99. It then removes all of the selected elements from the DOM.

The docs for remove make this clear:

Remove the set of matched elements from the DOM.

Upvotes: 3

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using attribute selector,

$('#FormA > :checkbox[value=-99]').remove();

Upvotes: 4

Bryan
Bryan

Reputation: 6752

Your selector will most likely work if you use $('#FormA :checkbox'), the way you have it right now, requires that the checkbox be an immediate descendant of the form.

Upvotes: 0

Mike Robinson
Mike Robinson

Reputation: 25159

I think this might work:

$("#FormA :checkbox[value=-99]").remove()

Upvotes: 3

Related Questions