Jamie Taylor
Jamie Taylor

Reputation: 3530

Remove two items from separate arrays in the same position

I've got two separate arrays which look like this

12-Jan-12 (remove), 14-Mar-12 (remove)
£139, £187

When someone click the remove button in array I need it to remove the the one from the second array in the same position

So if i clicked remove on the 12-Jan-12 then i want it to remove £139 from the second array

Here's some code I have already to remove one from the first array

$('.delete-date').live('click', function() {

    $(this).closest('.myDate').remove();

});

Here's my HTML

<span class="dates">
    <span class="myDate">
        12-jan-12
        <span class="delete-date" title="remove this tag" />
    </span>,
    <span class="myDate">
        14-mar-12
        <span class="delete-date" title="remove this tag" />
    </span>,
</span>

<span class="costs">
    <span class="myCost">
        £139
    </span>,
    <span class="myCost">
        £187
    </span>,
</span>

Any ideas?

Thanks in advance

Upvotes: 2

Views: 96

Answers (3)

JohnP
JohnP

Reputation: 50039

You can use the index() method to get the index of the element and find the matching one in the second set.

$('.delete-date').live('click', function() {
    var pos = $(this).closest('.myDate').index();
    $(this).closest('.myDate').remove();
    $('.costs .myCost').eq(pos).remove();
});

http://api.jquery.com/index/

Upvotes: 1

RoToRa
RoToRa

Reputation: 38431

With jQuery you can get the index of an sibling with the .index() method and use the .eq() method to select an element based on it's index. So:

var d = $(this).closest('.myDate');
var index = d.index();

d.remove();

$(".costs .myCost").eq(index).remove();

NB: Instead of .live(), you should consider using delegate() (or .on() with jQuery 1.7), as it's much more efficient.

Upvotes: 1

c4urself
c4urself

Reputation: 4287

You're looking to combine

.index() 

and

.eq()

For example, in a click event handler

var dateIndex = $(".dates").index($(this));
prices.eq(dateIndex).hide();

Upvotes: 0

Related Questions