简体   繁体   中英

How do I remove specific elements using an jQuery .each loop?

Assume I have an HTML document containing:

<form id = "my_form">
    <input type = "text" />
    <input type = "text" />
    <input type = "text" />
    <button type = "button" onclick = "removeGoodInputs()">Do the job</button>
</form>

I want to get rid of the inputs values which satisfy some condition (given in my JS). I have tried creating my removeGoodInputs() function (as below), but this removes all inputs from the form. How can I resolve this issue?

function removeGoodInputs() {
    $("#my_form input").each(function() {
        if(this.attr("value") == 10)
            $(this).remove();
    });
}

attr is one the methods of jQuery object, you should first convert the DOM object this to a jQuery object and then use jQuery methods, $(this).attr("") , also you can use val method for getting/setting values of form controls instead of attr and you don't need each , you can use Attribute Equals Selector :

function removeGoodInputs() {
    $("#my_form input[value='10']").remove();
}

$("#my_form input[value='10']") selects the inputs that their values are 10 .

Another way to solve this is to use .filter [docs] :

$("#my_form input").filter(function() {
    return this.value === '10';
}).remove();
function removeGoodInputs() {
 $("#my_form input").each(function() {
  if($(this).val() == 10) $(this).remove();
 });
}

.attr() is a jQuery method so it can only be called on a jQuery object. Further, in jQuery .val() is the easier way to get the value (a shortcut).

So, this line of your code is not correct:

if(this.attr("value") == 10)

I would recommend either:

if (this.value == "10")      // plain javascript

or:

if ($(this).val() == "10")   // jQuery

Note, I also changed the comparisons to be strings since that is what .value returns and it's better to not rely on an automatic type conversion.

You can see it work here: http://jsfiddle.net/jfriend00/HMemp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM