Click and add id in the array. If you click again, remove this id

0

I have a problem, I have a list and when the user clicks it adds the id of this <li> to an array, but I want it when I click again on that <li> , that id is removed from the id. Here's the JSFIDDLE .

HTML:

<ul>
  <li id="1">Teste 1</li>
  <li id="2">Teste 2</li>
  <li id="3">Teste 3</li>
  <li id="4">Teste 4</li>
  <li id="5">Teste 5</li>
  <li id="6">Teste 6</li>
  <li id="7">Teste 7</li>
  <li id="8">Teste 8</li>
  <li id="9">Teste 9</li>
  <li id="10">Teste 10</li>
</ul>
<a href="#" id="show">Exibir selecionados</a>
<div id="retorno"></div>

JavaScript

$(function(){
  var idsSelecionados = [];
  $('li').click(function(){
   var id = $(this).attr('id');
   idsSelecionados.push(id+',');
   $(this).toggleClass("active");  
  });

    $('#show').on('click', function(){
        $.each(idsSelecionados, function(i, val){
          $('#retorno').append(val);
        });
    });
});
    
asked by anonymous 26.07.2015 / 20:51

2 answers

2

I think one solution to the question is:

$(function(){
  var idsSelecionados = [];
  $('li').click(function(){
   var id = $(this).attr('id');
   var idx = idsSelecionados.indexOf(id+',');
   if (idx == -1) {
     idsSelecionados.push(id+',');
   } else {
     idsSelecionados.splice(idx, 1);
   }
   $(this).toggleClass("active");  
  });

    $('#show').on('click', function(){
        $.each(idsSelecionados, function(i, val){
          $('#retorno').append(val);
        });
    });
});

Comments:

The delete method can be used to exclude the element from the array, but there is a "hole" with the value undefined , the Array.splice method does not leave this "hole".

Since I do not know why I put the comma along with id , I left it. But it can be a misnomer during programming, if necessary, modify to stay as desired.

I'm missing something that was not the main object of the question and I'm not sure: toggleClass I think it only adds the class active , so you still need to find out how to remove the active class and put those instructions inside the if and else .

    
26.07.2015 / 21:49
1
var lista = [];

$("li").click(function(){
    var id = $(this).attr("id");
    var index = lista.indexOf(id);

    if(index > -1) {
        lista.splice(index, 1);
    } else {
        lista.push(id);
    }
    $("#retorno").html(lista);
});
    
26.07.2015 / 22:02