Jacob Valenta
Jacob Valenta

Reputation: 6769

Insight into jQuery's .find()? (Unexpected results)

I have a "category tree" with several select boxes. When you choose a category for an item to be in, it loads the children categories and displays them in the next select box.

On .submit() for the form, I have it delete the first .category from the DOM. Once the last one is left, it gives the name attribute to the last .category.

The twist comes when there are multiple item forms on a page. What I have done is iterate over the .items with jQuery's .each() and then from there, use jQuery's .find() to find the categories within an item.

The While loop that I am using creates a endless loop. I have used console.log() to output my variables throughout the execution of the script, and I don't think .find() is returning what I think it is.

html:

<div class="item">
    ....
    <div class="category"></div>
    <div class="category"></div>
    ....
</div>

javascript:

$('#transaction-form').submit(function(){
    $('.item').each(function(){
        var index = $(this).index();
        var category = $(this).find('.category');
        while (category.length > 1){
            $($(category)[0]).parent().remove();
        }
        $(category[0]).attr('name', 'form-' + index.toString() + '-category');
    });
});

Calling category.length in the while statement returns 2, as it should. I don't think the returned value of .find() is a jQuery object.

Upvotes: 0

Views: 62

Answers (2)

Try

$('#transaction-form').submit(function(){
    var x = $('.item').has('.category');
    x.not(x.last()).remove();
    });
});

References

.has()

.last()

.not()

.remove()

Upvotes: 1

TheNickmaster21
TheNickmaster21

Reputation: 275

Removing your category parent entries doesn't actually remove it from the Jquery object. So you got an infinite loop because your length never actually changes...

Upvotes: 1

Related Questions