简体   繁体   中英

I can't seem to empty a javascript array

I know there are a lot of these questions on Stackoverflow but none of them work for me. I would like to post my own code and try and find out what I am doing wrong.

So, I have a function that adds a bunch of items to an array. The page is never refreshed, as is the way it is designed. So when that same function is called again the array MUST be emptied because:

  1. Items added to an array are linked to a specific item on the page that the user selected.
  2. When a new item is selected the old item's things should not be shown in the array. Only the new item's things.
  3. The array is populated from checkbox values and that array is then used to create different checkboxes on a popup modal form.

Here is the code to populate the array:

// Here I tried emptying the array with below mentioned methods. The array is defined outside of the function. I have also tried defining it inside.
    var count = 0;
  var optionsSelected = 0;
  $('input[name="extrasSelected"]:checked').each(function() {
      var selected = $(this).val().split("|");
      extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
      optionsSelected++;
      count++;
  });

  $('input[name="extrasSelected"]:not(:checked)').each(function() {
    var notSelected = $(this).val().split("|");
      extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
      count++;
  });

  extras.sort();

This entire thing is working perfectly. Except when I select a new item. The popup displays and checkboxes are created with the previous item's things as well as checkboxes with the new item's things.

I have tried to use:

extras = [];
extras.pop();
extras.length = 0
while (extras > 0) {
    extras.pop();
}

Actually, I have tried all methods seen on stackoverflow and google. So I am guessing that I am doing something wrong.

Any help would be greatly appreciated!

EDIT

Additional Code As Requested:

var extras = [];
$("#doLookup").click(function() {  
  var count = 0;
  var optionsSelected = 0;
  $('input[name="extrasSelected"]:checked').each(function() {
      var selected = $(this).val().split("|");
      extras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked'];
      //alert(extras[0][1]);
      optionsSelected++;
      count++;
  });

  $('input[name="extrasSelected"]:not(:checked)').each(function() {
    var notSelected = $(this).val().split("|");
      extras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked'];
      //alert(extras[0][1]);
      count++;
  });

  extras.sort();

   if (extras.length > 0) {
                    optionalsJSHead = '<table width="100%"><tr><th style="width: 40%;"><b>Optional Extra</b></th><th style="text-align:right;width:15%"><b>Retail</b></th><th style="text-align:right;width:15%"><b>Trade</b></th><th style="text-align:right;width:15%"><b>Market</b></th><th style="text-align:right"><b>Include</b></th></tr>';
                    optionalsJSBody = '';
                    if (parseInt(year) === parseInt(guideYear)) {
                      for (i = 0; i < extras.length; ++i) {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" disabled="disabled"/></td></tr>';
                      }
                    } else {
                      for (i = 0; i < extras.length; ++i) {
                        if (extras[i][4] == 'notChecked') {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'"/></td></tr>';
                        } else {
                          optionalsJSBody += '<tr><td>'+extras[i][0]+'</td><td align="right">R '+extras[i][1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][2].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right">R '+extras[i][3].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")+'</td><td align="right"><input class="chckDis" type="checkbox" name="extrasSelectedAdjust" id="'+ extras[i][0] +'" value="'+ extras[i][0] +'|'+ extras[i][1] +'|'+ extras[i][2] +'|'+ extras[i][3] +'" checked /></td></tr>';
                        }
                      }
                    }
                    optionalFooter = '</table>';
                    optionalsJS = optionalsJSHead + optionalsJSBody + optionalFooter;
                  }
});

From my understanding, you can create a temporary array, populate it with new values and then assign it to extras variable. See the code below:

 var extras = []; // actual array whose items you want to use $("#doLookup").click(function() { var tmpExtras = []; // temporary array to get the new items you want. var count = 0; var optionsSelected = 0; $('input[name="extrasSelected"]:checked').each(function() { var selected = $(this).val().split("|"); tmpExtras[count] = [selected[0], selected[1], selected[2], selected[3], 'checked']; //alert(extras[0][1]); optionsSelected++; count++; }); $('input[name="extrasSelected"]:not(:checked)').each(function() { var notSelected = $(this).val().split("|"); tmpExtras[count] = [notSelected[0], notSelected[1], notSelected[2], notSelected[3], 'notChecked']; //alert(extras[0][1]); count++; }); tmpExtras.sort(); // now assign tmpExtras to extras array, so that // you can get the new items extras = tmpExtras; // ... rest of code that uses extras 

If you should set array as empty before adding some value to the array. I think you should set it in both places before you try to fill it: extras[count] = []; extras[count] = .... extras[count] = []; extras[count] = .... . And why do you need the array of array? maybe you should used just array and every time rewrite it? like:

extras = [selected[0], selected[1], selected[2], selected[3], 'checked'];

then no needs to set array like empty before filling.

Your click event is bound to a single item. #doLookup is an id selector which means that there is a single item with the id="doLookup" in the document.

How do you intend to let the function know that the array needs to be emptied?

A simple fix would be to bind the click event to another selector such as .doLookupClass etc and then check inside the function when a different item was selected and empty the array.

It would seem I made a rookie mistake. The array was being emptied. However since I am creating textboxes with javascript I forgot to empty the div before adding the new ones, causing the old ones to still display. And I didn't post that part of the code so that is why you guys probably couldn't assist.

I changed

$("#myDiv").append(OptionalsJS);

to

$("#myDiv").empty().append(OptionalsJS);

What a stupid mistake... X_X anyway, thanks for the assistance anyway!

Maybe the whole thing can be done in a much easier fashion?

See here for a working example

 var extras = []; // actual array $("#doLookup").click(function() { extras = []; // temporary array $('input[name="extrasSelected"]').each(function() { with ($(this)){ var cb=val().split("|"); var state=(is(':checked')?'':'un')+'checked'; } extras.push([cb[0], cb[1], cb[2], cb[3], state]); }); $('#show').html(JSON.stringify(extras)); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type=checkbox value="a|b|c|d" name="extrasSelected" /><br/> <input type=checkbox value="e|f|g|h" name="extrasSelected" /><br/> <input type=checkbox value="i|j|k|l" name="extrasSelected" /><br/> <input type=checkbox value="m|n|o|p" name="extrasSelected" /><br/> <input type=checkbox value="q|r|s|t" name="extrasSelected" /><br/> <input type=checkbox value="u|v|w|x" name="extrasSelected" /><br/> <input type="button" id="doLookup" value="go"/> <div id="show" /> 

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