1

I have a function that takes all the items in a list that are not checked and creates a new array out of them.

// Allows user to remove keywords from the locaStorage
$('#clearChecked').click(function() {
  currentArray = [];
  $('.check').each(function() {
    var $curr = $(this);
    if (!$curr.is(':checked')) {
      var value = $curr.parent().text();
      currentArray.push(value);
      localStorage.setItem('keyWords', JSON.stringify(currentArray));
      loadKeyWords();
    } else {
      $curr.parent().remove();
    }
  });
});

The problem is that if I check all the items it wont remove any. Or if one item is left it wont let me remove the last item.

But it will allow me to remove as many items as I want as long as there is one item left.

How can I change my function to allow me remove the last item in the array or all of the items if they are checked.

I am outputting the array like this,

// Generate random id for id of keywords
function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

 var x = guidGenerator();
      $('#keyWords').prepend('<li class="list-group-item" data-style="button"><input id="'+ x +'" class="check" name="check" type="checkbox"><label for="'+ x +'">'+localArray[i]+'</label></li>'); 

In the html file

<button id="clearChecked">Clear Checked Items</button>

<ul id="keyWords">
    <li class="list-group-item" data-style="button">
        <input id="4667ac55-5de4-df61-9b82-9b50c728adea" class="check" name="check" type="checkbox">
        <label for="4667ac55-5de4-df61-9b82-9b50c728adea">qedfeqdeqdeq</label>
    </li>
</ul> 
Haring10
  • 1,517
  • 1
  • 19
  • 37
wuno
  • 9,547
  • 19
  • 96
  • 180
  • I updated the question with the js that outputs the html – wuno Jan 10 '16 at 05:36
  • 1
    Side note: Your `ID` on the input cannot have spaces. – Haring10 Jan 10 '16 at 05:40
  • That is a good point. And when I remove the id all together I cannot select the items. But the id is being created dynamically which can be any string the user creates. – wuno Jan 10 '16 at 05:44
  • Don't do that. Store the string that the user creates in a javascript object with the key as the `ID` (generate a random string) and then the value what the user creates. – Haring10 Jan 10 '16 at 05:47
  • @wuno That might led to some security issues. Use a key number for `id` instead and maintain the table of key-value in javascript. – maowtm Jan 10 '16 at 05:49
  • Ok awesome. You guys are super helpful thank you. Is it possible the id situation is what is stopping the last object from being removed? – wuno Jan 10 '16 at 05:51
  • I edited my code with a new function that creates a random string and updated the html output to include the random string as the id. The problem still persist but the id is working. – wuno Jan 10 '16 at 05:58

2 Answers2

1

Just add the code in check box clicked event:

if($('.check:checked').length == $('.check').length) {
    window.localStorage.clear();
    location.reload();
    return false;
}
timss
  • 9,982
  • 4
  • 34
  • 56
deep
  • 350
  • 1
  • 7
0

I solved the issue (at least on my side) by:

  1. Changing the ID of the input and the for of the label to a unique string without any spaces
  2. Added }); to below the jQuery you posted, as it was not closing the main original function.

    <button id="clearChecked">Clear Checked Items</button>
    
    <ul id="keyWords">
    <li class="list-group-item" data-style="button">
        <input id="link_0" class="check" name="check" type="checkbox">
        <label for="link_0">I am a link</label>
    </li>
    <li class="list-group-item" data-style="button">
        <input id="link_1" class="check" name="check" type="checkbox">
        <label for="link_1">I am a link</label>
    </li>
    <li class="list-group-item" data-style="button">
        <input id="link_2" class="check" name="check" type="checkbox">
        <label for="link_2">I am a link</label>
    </li>
    </ul>
    
    $('#clearChecked').click(function() {
      currentArray = [];
      $('.check').each(function() {
        var $curr = $(this);
        if (!$curr.is(':checked')) {
          var value = $curr.parent().text();
          currentArray.push(value);
          localStorage.setItem('keyWords', JSON.stringify(currentArray));
          loadKeyWords();
        } else {
          $curr.parent().remove();
        }
      }); // only closing the $('.check').each(function() { function
      }); // closing the $('#clearChecked').click(function() { function
    

Check out this fiddle to see it working

EDIT:

Regarding the GUID that you posted... fix it.

function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for( var i=0; i < 5; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

return text;
}

Credit for makeid function goes to csharptest.det

Community
  • 1
  • 1
Haring10
  • 1,517
  • 1
  • 19
  • 37
  • Ya I had posted an edit with a random string generating the id. And I am sorry I didnt add the closing is the function. I was just trying the logic of my function. I was thinking this was a logical error not a syntax error. The code works, it just wont let me remove the last item in the array by checking it. – wuno Jan 10 '16 at 06:03
  • @wuno try the fiddle. the removing the last item works on the fiddle. – Haring10 Jan 10 '16 at 06:04
  • Yes I can see that. This function was working for me as well just fine. It was not till I added the label and ID and some css that I started having this problem. It is always nice when you put the finishing touches on a program all to have it break when you're supposed to be done. Can you think of anyway I can trouble shoot this? Like alerts in the clear function for errors? or maybe if the array becomes empty add some fake data to it then remove it after creating the array again? – wuno Jan 10 '16 at 06:09
  • @wuno having stuff break is what programming is all about - solving problems. But you can debug it. You can put logs inside each function, I personally don't like using alerts for debugging as logs appear in the console with line numbers, etc. If this code is working for you, and it breaks with the rest of your code, then there is something else that is the problem - not in this part of the code. – Haring10 Jan 10 '16 at 06:13