Selection and Deselection of elements by user in jQuerySelecting thumbnail imagesWe have a group of images with different id and user can select or deselect the images by clicking on it. All images have common class ( class='select_img' ).We will keep one array which will add the id of the image on selection and remove the id if it is deselected. Selecting records in a tableWe will display records as rows in a table and user can select or deselect records. For each selection or deselection records Ids can be added or removed from JavaScript array.Tutorial on how to collect records from database table Adding style while selecting , removing style while deselecting.We will add border and change the background color of selected element by adding style to the element. While deselecting we will remove the style.Here is the style declaration <style> .checked {border:solid 2px red;background:#ffff00;} </style>To add or remove style
Adding and removing record IDWe will declare one JavaScript array (record_selected )and on every selection of the record ( or image ) we will read the ID of it and add it to the array by using push function. Similarly once we deselect the element the respective ID will be removed from the array by using splice function.As we will be using the array inside functions so we will declare it as global array. Here it is how we will collect the id and add to our Array ( on Selection ) var my_id=this.id;// collect id record_selected.push(my_id);// add to arrayHere it is how we will remove the id after deselection of the element.
To display all elements of the array we will use one div tag
$('#display').html("ID of selected images :"+record_selected);The complete JQuery code is here, you will get full code with HTML and Style in above DEMO pages <script> $(document).ready(function() { //////////////////////// var record_selected = new Array();// declar global array ////////////// $('#d2').on('click', ".select_record", function () { var aa = $(this) if( !aa.is('.checked')){ aa.addClass('checked'); var my_id=this.id; record_selected.push(my_id); } else { aa.removeClass('checked'); var my_id=this.id; var index = record_selected.indexOf(my_id); if (index > -1) { record_selected.splice(index, 1); } } $('#display').html("ID of selected images :"+record_selected); }) /////////////////// })</script> ![]()
This article is written by plus2net.com team.
![]() |
Most Popular JQuery Scripts | |
1 | Two dependant list boxes |
2 | Calendar with Date Selection |
3 | Data change by Slider |
4 | Show & Hide element |