capture selected value of datatables (Jquery) and save in array

1

I am using Jquery datatable, I would like that when selecting values from the table, they are stored in an array. I tried the following.

$('#tblMsnToColab tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );


     $('#tblMsnToColab tbody').on( 'click', 'tr', function () {
        i=0;
         idMen = tblColab.row( this ).data();
         colabArray = [];
        colabArray[i]=idMen['id'];
        i++;
    });

My problem is that by clicking on the tr, the variable i always assigned it the 0.

    
asked by Lorenzo Martín 28.08.2018 в 11:59
source

2 answers

1

You can use the function jQuery each which allows you to pass a counter as an input parameter:

    $("#tblMsnToColab>tbody>tr").each(function(i) {
       $(this).on('click', function() {
          $(this).css("background-color", "grey");
          array.push(i); // guardo el contador, pero puedes guardar un atributo 'data' o lo que quieras
          alert(array);
       });                  
    });

Here's an example: link

    
answered by 28.08.2018 / 17:10
source
0

What has worked for me is the following.

 var colabArray = [];
    var i=0;

 $('#tblMsnToColab tbody').off( 'click', 'tr');
$('#tblMsnToColab tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) { //Si estoy deseleccionando
        $(this).toggleClass('selected');
        idColab = tblColab.row( this ).data(); //Tomo el id
        $.each(colabArray,  function( key,idColabAr ) {
            if(colabArray[key]==idColab['id']){ //Busco y comparado id el array
                colabArray.splice(key, 1); //Elimino desde la posicion empezando por 0,un elemento
                i=i-1; //Tengo que restar uno a la i, ya que elimino un elemento.
            }
        });

    }

    else{ //Estoy marcando
        idColab = tblColab.row( this ).data();
        colabArray[i]=idColab['id'];
        i++;
        $(this).toggleClass('selected');
    }

    console.log(colabArray.join(';'))//Esto es para separar los elementos por ;

    $("#creaMensaje").on("hidden.bs.modal", function() {
        colabArray.length=0; //Borro el array al salir
        i=0;
    });
});

The idea is in a datatable, it makes multi selection, when I click and select a row, I save the value in an array, when I click on a selected row, I deselect the row, I look for that element in the array by going through this and I delete the element from the array.

I'm sure it can be done in some other more efficient way, I appreciate some improvement. Thanks

    
answered by 28.08.2018 в 16:39