简体   繁体   中英

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

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM