Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda