This tutorial shows how to build selection and deselection without checkboxes. Users click images or table rows, the selected state is shown with a CSS class, and selected record IDs are stored in a JavaScript array.
Give each selectable image a unique ID and a shared class such as select_img. Clicking an image toggles the selected state and adds/removes its ID from the array.
Demo: select and deselect thumbnail images →
The same approach works with table rows or record cards. Each record has a stable ID that is added to or removed from the selection array.
Related SQL tutorial: collect records from a database table.
Demo: select and deselect table records →
.checked {
border: 2px solid red;
background: #ffff00;
}
const $item = $( this );
$item.addClass( "checked" );
$item.removeClass( "checked" );
The original example uses push() to add an ID and splice() to remove it. That behavior is preserved.
Related JavaScript tutorials: Array.push() and Array.splice().
const id = this.id;
recordSelected.push( id );
const id = this.id;
const index = recordSelected.indexOf( id );
if ( index > -1 ) {
recordSelected.splice( index, 1 );
}
$( "#display" ).text(
"Selected IDs: " +
recordSelected.join( ", " )
);
Use .text() because the selected IDs are plain text, not HTML.
Delegation is useful when rows/items may be inserted later by AJAX or other scripts.
$( function () {
const recordSelected = [];
$( "#d2" ).on(
"click",
".select_record",
function () {
const $item = $( this );
const id = this.id;
const selected =
$item.hasClass( "checked" );
if ( !selected ) {
$item.addClass( "checked" );
if (
!recordSelected.includes( id )
) {
recordSelected.push( id );
}
} else {
$item.removeClass( "checked" );
const index =
recordSelected.indexOf( id );
if ( index > -1 ) {
recordSelected.splice(
index,
1
);
}
}
$( "#display" ).text(
"Selected IDs: " +
recordSelected.join( ", " )
);
}
);
});
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.