Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!