Fabrizio Fenoglio
Fabrizio Fenoglio

Reputation: 5947

Remove a given number of elements with Jquery

I have 10 divs with the same name class example my-div. When an event is triggered in a change of a select input I want to remove the number of that divs pair to the number of the input.

This is an example of what I'm trying to do:

Html

<select id="delete">
   <option value="0">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

<div class="my-div"></div>
<div class="my-div"></div>
<div class="my-div"></div>
<div class="my-div"></div>
<div class="my-div"></div>
<div class="my-div"></div>

Jquery

$(document).on('change','#delete',function(){

   var value = $(this).val();

   // here I need to remove the divs pair the variable value

});

Upvotes: 0

Views: 68

Answers (3)

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

Do you want to remove, or do you just want to hide? Literally removing the divs will add a bit complexity to your logic if, say, you select a 1 and then go back to 4.

If all you want is hide, then you can try something like this:

var divs = $('.my-divs');

// this way of tacking on events is kinda inefficient, btw
$(document).on('change', '#delete', function () {
    var idx = +($(this).val());
    divs.show()
        .filter(':gt(' + idx + ')')
        .hide()
        ;
});

Upvotes: 0

hsz
hsz

Reputation: 152216

Just try with:

$(document).on('change','#delete',function(){
   var value = +$(this).val();
   $('.my-div:lt(' + value + ')').remove();
});

http://jsfiddle.net/VE7uu/1/

Upvotes: 1

Pete
Pete

Reputation: 58422

If I understand you correctly, you can use jQuery slice to get the number you want:

$(document).on('change','#delete',function(){
    var value = parseInt($(this).val());
    if (value > 0) {
        $('.my-div').slice(0, value).remove();
    }
});

Example

Upvotes: 2

Related Questions