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

Asked

Viewed 239 times

1

I have a problem, I have a list and when the user clicks it adds the id of this <li> in an array, but I want when it click again on that <li>, this id is removed from id. Here it is in 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);
        });
    });
});

2 answers

2


I think a 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);
        });
    });
});

Remarks:

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

As I don’t know why I put the comma together with the id, left. But it may be a mistake during programming, if necessary, modify to stay as desired.

Something missing that was not the main object of the question and I’m not sure: toggleClass I guess it just adds the class active, then you still need to find how to remove the class active and place these instructions inside the if and of else.

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);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.