Multi-select checkboxes with tablesorter - javascript

I have a Python script which generates an HTML table. The final column of the table contains checkboxes. I want to use the Shift key to select multiple checkboxes. So, I've incorporated this Javascript.
However, I'm sorting the table columns after loading using tablesorter (and after calling the above Javascript). Furthermore, the user can also sort columns by clicking on column headers. This results in the wrong checkboxes being selected after the user uses Shift-click.
So far I have tried:
moving the select multiple checkboxes javascript to after the sorting (which seems logical to me), but then the sorting functionality does not work
the other javascript answers to that question (How can I shift-select multiple checkboxes like GMail?) but then multi-select does not work
other Googled code (like this) - but again multi-select does not work
The code:
<script src='shift-click-select.js'></script>
<script src='jquery-latest.js'></script>
<script src='jquery.tablesorter.min.js'></script>
<script>
//Javascript function to sort table "my_table" by default on first column (0,0) and then on second column (1) in ascending order (0).
$(function() {
$("#my_table").tablesorter({sortList:[[0,0],[1,0]]});
});
</script>
<table id="my_table" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
<td><input type="checkbox" name="%s" class="chkbox" /></td>
...
</table>
note: shift-click-select.js is from answer mention above.
My guess is that I might need to re-number the checkboxes every time the table is resorted, but I'm hoping there is an easier way?

I suspect that you copied the code from this post almost exactly:
<script type="text/javascript">
var lastChecked = null;
$(document).ready(function() {
var $chkboxes = $('.chkbox');
$chkboxes.click(function(e) {
if(!lastChecked) {
lastChecked = this;
return;
}
if(e.shiftKey) {
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);
$chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).attr('checked', lastChecked.checked);
}
lastChecked = this;
});
});
</script>
The problem you're probably experiencing is caused by the var $chkboxes = $('.chkbox'); invoked on the document being ready. That's declaring a list of .chkbox objects in their initial order when the page loads. tablesorter then changes the order.
If what I'm assuming is correct, then getting it to work properly would be as simple as changing:
var $chkboxes = $('.chkbox');
$chkboxes.click(function(e) ...
to:
$('.chkbox').click(function(e) {
var $chkboxes = $('.chkbox');
This way the checkbox order is determined on each click rather than once on page load.
It would help if we got to see the contents of your shift-click-select.js.

using this i was able to achieve desired function
$(function() {
var $table = $('#myTable');
var $chkboxes,lastChecked = null;
$table
.tablesorter({sortList:[[0,0],[1,0]]})
.on('sortEnd',function() {
$chkboxes = $table.find(':checkbox');
})
.on('click',":checkbox",function(e){
if(!lastChecked) {
lastChecked = this;
return;
}
if(e.shiftKey) {
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);
var last = lastChecked.checked; //cache as we might change its value
$chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', last);
}
lastChecked = this;
});
});
notice i changed attr('checked' to prop('checked' as checked="false" is an invalid state

I used senordev's solution on my app, but found a large pitfall in my testing, which I've resolved below.
senordev's implied solution:
$('.chkbox').click(function(e) {
var $chkboxes = $('.chkbox')
if(!lastChecked)
{
lastChecked = this;
return;
}
if(e.shiftKey)
{
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);
$chkboxes.slice(Math.min(start,end), Math.max(start,end)+1).prop('checked', lastChecked.checked);
}
lastChecked = this;
});
The issue I ran into was regarding filtration, if I filtered out some rows, and shift-selected, the script would select all the hidden rows in between as well (sometimes thousands). Therefore, I added a small fix:
var $chkboxes = $('.chkbox')
to
var $chkboxes = $('.chkbox').filter(':visible');
Additional corner cases I accounted for include resetting the lastChecked value whenever the sort changes (because lastChecked might now be on a completely different page) and when the filters change (because lastChecked might not be visible anymore).
$("table").tablesorter({
...
})
// Clear the lastChecked to avoid unexpected selections.
// e.g. lastChecked might not be on the visible page anymore.
.bind("sortStart",function() {
lastChecked = null
}).bind("sortEnd",function() {
lastChecked = null
}).bind('filterEnd', function() {
lastChecked = null
});

Related

How to iterate over htmlCollection

I'm having some difficulty with this. In Backbone, I have a function like this:
functionOne: function(){
$('#myTExtbox-' + budgetLine.attr('id')).on('change keyup paste', function(){
that.mySecondFunction(this);
});
}
In this case, the this is a textbox, which is in a table, inside a div. Then:
mySecondFunction: function(tb){
var tbody = tb.parentElement.parentElement.parentElement.parentElement.parentElement;
//gets main parent, which is a tbody, inside a table, inside a div
}
I then want to iterate over tbody, to go through each row and find a textbox in a specific cell. The problem is that this code:
$.each(tbody, function(index, item){
cost = item;
var t= index;
});
Doesn't seem to allow me to get to any of the items. In this example, if I try to do something like:
item.getElementById('test');
I get an error:
TypeError: Object #<HTMLCollection> has no method 'getElementById'
Why can't I iterate over this object and access objects within?
Thanks
UPDATE
Here's a fiddle: http://jsfiddle.net/HX8RL/14/
Essentially, what should happen is this: When a text box changes, I want to iterate over all the rows in the tb's parent table and sum all the Tb values. Keeping in mind, all the tb's in the same cell position, as there could be other tb's in other places that I dont want to include.
There wont be any collection of TBody
try using children() instead
$.each(tbody.children('tr'), function(index, item){
cost = item;
var t= index;
});
Demo Fiddle
Iterate over all input elements directly to get values.
var tbody = tb.parentElement.parentElement.parentElement;
alert(tbody.id);
var input = $('#tbody').find('input');
alert(input);
console.log(input);
for (var i = 0; i < input.length; i++) {
alert(input[i].value);
alert(i);
}
See fiddle-http://jsfiddle.net/HX8RL/18/
I think there are a few things going wrong here. You know you can only have one ID per page? So you have to do document.getElementByid('test') instead.
Since you are also using jQuery you can use the find function, item.find('#test'). But I think this wouldn't solve you problem. Not sure what you want to achieve, maybe I can help you if you explain a bit more in detail what your problem is.
Also
tb.parentElement.parentElement.parentElement.parentElement.parentElement;
can be written as (in jQuery)
$(tb).parents('tbody');
I've setup a fiddle, maybe it can help you.
Code used in fiddle:
var myFuncs = (function() {
function funcA() {
$('input').on('keyup', function() {
funcB(this);
});
}
function funcB(myInput) {
var $table = $(myInput).parents('table');
$table.find('tr > td > input').each(function() {
var $input = $(this);
if($(myInput).attr('id') != $input.attr('id'))
$input.val("I'm called from another input");
});
}
return {
funcA : funcA
}
})();
myFuncs.funcA();

performing sortable using JavaScript

i have a situation where i need to achieve this, in a table having n rows. if i click on a row in a table and then click on another row. the content in row of first click should go to content in row of second click and then each row should be shifted by on step backward or forward. this can be taken equivalent to JQUERY sortable.
Example:
|1|2|3|4| if i click on 1 and 4 then it should be |2|3|4|1|
how to record two clicks, and the contents of my rows are div elements containing many input elements. I thought of this idea and is this a good way to achieve sortable or is there a still better way, i want to do it using java script.
thanks in advance.
my script fucntion goes like this. I really should have thought for a little longer. i used flags here, i got two questions more, can i do that with out flags?, is there a better way?
<script>
var flag=0;
var id1;
var id2;
function Myfunction(id)
{
if(flag==0)
{
id1=id;
flag=1;
}
else
{
id2=id;
var x=document.getElementById(id1).innerHTML;
var num1=parseInt(id1);
var num2=parseInt(id2);
for(var i=num1;i<num2;i++)
{
var j=i.toString();
var k=(i+1).toString();
document.getElementById(j).innerHTML=document.getElementById(k).innerHTML;
}
document.getElementById(id2).innerHTML=x;
flag=0;
}
}
</script>
I made up a little http://jsfiddle.net/zxKeg/. Works with jQuery only, no additional plugins needed. Hope this will help you!
JS Code:
$(document).ready(function() {
var $table = $('table');
var $toCopy = null;
$table.on('click', 'tr', function() {
if($toCopy === null || $toCopy[0] == this) {
$toCopy = $(this);
}
else {
$toCopy.remove();
$(this).after($toCopy);
$toCopy = null;
}
});
});

Recursive IDs and duplicating form elements

I have the following fiddle:
http://jsfiddle.net/XpAk5/63/
The IDs increment appropriately. For the first instance. The issue is when I try to add a sport, while it duplicates, it doesn't duplicate correctly. The buttons to add are not creating themselves correctly. For instance, if I choose a sport, then fill in a position, and add another position, that's all fine (for the first instance). But when I click to add another sport, it shows 2 positions right away, and the buttons aren't duplicating correctly. I think the error is in my HTML, but not sure. Here is the JS I am using to duplicate the sport:
$('#addSport').click(function(){
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $('div.kpSports').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#kpSport').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
});
Hoping someone has an idea, perhaps I've just got my HTML elements in the wrong order? Thank you for your help! I'm hoping the fiddle is more helpful than just pasting a bunch of code here in the message.
The problem is in your clearCloneValues function. It doesn't differentiate between buttons and other for elements that you do want to clear.
Change it to:
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined && element.attr('type') !== 'button'){
element.val('');
}
}
As #PHPglue pointed out in the comments above, when new positions are added, they are incorrectly replicated (I'm assuming here) to the newly cloned for
There is a similar problem with the add years functionality.
A quick fix would be to initialize a variable with a clone of the original form fields:
var $template = $('div.kpSports').first().clone();
Then change your addSport handler to:
$('#addSport').click(function () {
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $template.clone();
…
});
However, there are no event bindings for the new buttons, so that functionality is still missing for any new set of form elements.
Demo fiddle
Using even a simple, naive string based templates the code can be simplified greatly. Linked is an untested fiddle that shows how it might be done using this approach.
Demo fiddle
The code was simplified to the following:
function getClone(idx) {
var $retVal = $(templates.sport.replace(/\{\{1\}\}/g, idx));
$retVal.find('.jsPositions').append(getItemClone(idx, 0));
$retVal.find('.advtrain').append(getTrainingClone(idx, 0));
return $retVal;
}
function getItemClone(setIdx, itemIdx) {
var retVal = itemTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, itemIdx);
return $(retVal);
}
function getTrainingClone(setIdx, trainingIdx) {
var retVal = trainingTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, trainingIdx);
return $(retVal);
}
$('#kpSportPlayed').on('click', '.jsAddPosition', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var itemIdx = $container.find('.item').length;
$container.find('.jsPositions').append(getItemClone(containerIdx, itemIdx));
});
$('#kpSportPlayed').on('click', '.jsAddTraining', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var trainIdx = $container.find('.advtrain > div').length;
$container.find('.advtrain').append(getTrainingClone(containerIdx, trainIdx));
});
$('#addSport').click(function () {
var idx = $('.kpSports').length;
var newItem = getClone(idx);
newItem.appendTo($('#kpSportPlayed'));
});

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Having jQuery string comparison issues

I've got a fiddle going here to show what I'm trying to do.
I have a table that is generated dynamically, so the columns could appear in whatever order the user chooses. So, I'm trying to get the index of two specific headers so that I can add a CSS class to those two columns for use later.
You should use .filter() here instead (and whenever you need to restrict the element set), since your .each() return is getting thrown away, like this:
//Loop thru the headers and get the Supp elem
var suppCol = $("#my_table th").filter(function() {
return $(this).html() == "Supp";
});
//Loop thru the headers and get the Report elem
var reportCol = $("#my_table th").filter(function() {
return $(this).html() == "Report";
});
You can test the updated/working fiddle here. The alternative using .each() would look like tis:
var suppCol, reportCol;
$("#my_table th").each(function() {
var $this = $(this), html = $this.html();
if(html == "Supp") suppCol = $this;
if(html == "Report") reportCol= $this;
});
You can test that version here.

Categories

Resources