Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
Add new value and remove previously added value in an array (Javascript)

I'm currently using the DataTables plugin for my project.

I have an AJAX sourced datatable where you can only ever have one row selected, now because my datatable is done server-side I need to keep track of which one is selected when changing pages.

Therefore I have been using this solution but this only seems to work for multiple row selection

Now essentially what I want to happen is, when you select a new row it should add the new row id to the array but also remove the previously added row id from the array, so there should only ever be one result in the array at a time.

Visually for better understanding:

var selected = []

Click Row 1 after loading table = [row_1]

Click Row 2 removing row_1 and adding row_2 = [row_2]

var selected = [];

$("#example").DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": "scripts/ids-arrays.php",
    "rowCallback": function( row, data ) {
        if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
            $(row).addClass('selected');
        }
    }
});

$('#example tbody').on('click', 'tr', function () {
    var id = this.id;
    var index = $.inArray(id, selected);

    if ( index === -1 ) {
        selected.push( id );
    } else {
        selected.splice( index, 1 );
    }

    $(this).toggleClass('selected');
} );
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Instead of adding an element to the array, you could replace the whole array. It seems a bit wasteful to use an array to store a single element, but there you go.

selected.push( id );

becomes

selected = [id];
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda