1

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;
                  }
});
10
  • When and where are you emptying the array? Commented May 12, 2017 at 6:36
  • Oh, sorry.. I am trying to empty it before I add the new items to the array.. I left that out.. I will edit my question.. Commented May 12, 2017 at 6:38
  • `extras = new Array(); console.log(extras); you will see it is empty before you something else Commented May 12, 2017 at 6:38
  • Since the page never gets refreshed, you are only emptying your array once. Is there an event (e.g click of a button) that you can use to indicate that it's time to clear the extras array? Commented May 12, 2017 at 6:41
  • @mtizziani, It is not working. It is also the same as extras = []; any other ideas though? Commented May 12, 2017 at 6:41

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Seems to be same as put extras inside the click callback?
Still doing the same thing. :(
1

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] = .... . 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.

1 Comment

if I don't use extras[count] = .... then each checkbox that i iterate through replaces the next and the array then only contains the last item. Maybe I have a mistake there are well. I am not GREAT in javascript.. I am actually an entirely different programmer.. lol
1

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.

Comments

1

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!

Comments

1

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.