tcd
tcd

Reputation: 1605

reset a dynamic array with jQuery

I have a function that pushes a dynamic amount of numbers into an array when I click a button, the code looks like this:

$('#calculate').click(function(e) {

var foo = $(".foo"),
    A = [],
    B = [];

    //Push values
foo.each(function(){
  var $t = $(this),
    num = $t.val(),
    xnum = num * 2.42;
  A.push(xnum);
  B.push(num);
});

//more stuff down here... 
//.ajax() to run and print a calculation

I'm getting these values from <select> menus and then I have a button that removes the <select> menu that it accompanies using the .empty() function...

I run into a problem when I calculate, THEN delete one of the <select> menus and recalculate... The value from the deleted <select> is still included in my calculation!

I figured the easiest way to reset the array would be to use:

A.length = 0;
B.length = 0;

But for some reason these aren't reseting the arrays and the old values are still included in the new calculation...

Is there a better way I can totally clear the array before I start pushing items into it?

Upvotes: 1

Views: 2832

Answers (2)

Dave L.
Dave L.

Reputation: 9791

I would modify the other answer to be more like this:

$(".remove").click(function() {
  $(this).parent('.foowrap').fadeOut(function() {
    $(this).empty();
  });
});

Notice, it avoids two calls to parent and the global variable and adds the missing semicolon.

EDIT: saw you had 2 elements with the same id so changed my code to assume you will change remove to a class.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146201

Try this

$(document).on("click", "#remove", function() {
    $this=$(this);
    $this.parent('.foowrap').fadeOut(function() {
        $this.parent('.foowrap').empty();
    });
});

Update: Use class .remove instead of id #remove, id meant to be unique.

DEMO.

Upvotes: 1

Related Questions