I'm new to jquery and trying to debug a script that will hopefully allow the user to select multiple rows of a table using Shift+Click and set the checkboxes to selected. I found an example online and I'm trying to debug the code, but I'm getting to line where a function is called, but the function never gets entered. I'm not sure why?
Here is the script:
j$ = jQuery.noConflict();
j$(document).ready(function() {
if(j$) {
//alert('Jquery loaded successfully...');
}
console.log(j$('input[id$=btnSearch]'));
j$('input[id$=btnSearch]').click(function(){
console.log(j$('[id$=searchTable] > tbody tr'));
var trs = j$('[id$=searchTable] > tbody tr');
j$('tr').on('click', function(myEvent){
//call the RowClick function on click event
RowClick(j$(this),false,trs,myEvent)
})
});
});
//declare variable to store the most recently clicked row
var lastSelectedRow;
// disable text selection
document.onselectstart = function() {
return false;
}
function RowClick(currentrow, lock, rows, myEvent) {
console.log('******************************************* we are inside the RowClick function');
console.log(currentrow);
console.log(lock);
console.log(rows);
console.log(myEvent);
//if control is held down, toggle the row
if (myEvent.ctrlKey) {
toggleRow(currentrow);
}
//if there are no buttons held down...
if (myEvent.button === 0) {
//if neither control or shift are held down...
if (!myEvent.ctrlKey && !myEvent.shiftKey) {
//clear selection
clearAll(rows);
//toggle clicked row
toggleRow(currentrow);
}
//if shift is held down...
if (myEvent.shiftKey) {
console.log('************************************** we are in the shift key branch');
console.log(currentrow);
console.log(currentrow.index());
console.log(rows);
console.log('************************************** we are calling the toggleRow function');
toggleRow(currentrow);
console.log('************************************** we have called the toggleRow function');
//pass the indexes of the last selected row and currently selected row along with all rows
selectRowsBetweenIndexes([lastSelectedRow.index(), currentrow.index()], rows)
}
}
}
function toggleRow(row) {
console.log('******************************* we are inside the toggleRow function');
console.log(row);
if (!row.hasClass('header-row')){
console.log('****************************** we are inside the row does not have the header-row class');
lastSelectedRow = row.toggleClass('selected');
}
}
function selectRowsBetweenIndexes(indexes,rows) {
//sort the indexes in ascending order
indexes.sort(function(a, b) {
return a - b;
});
//for every row starting at the first index, until the second index...
for (var i = indexes[0]; i <= indexes[1]; i++) {
//select the row
j$(rows[i+1]).addClass('selected');
}
}
function clearAll(rows) {
j$('.selected').removeClass('selected');
}
I get to this line:
console.log('************************************** we are calling the toggleRow function');
and the next line output is this line:
console.log('************************************** we have called the toggleRow function');
The toggleRow function is never entered. I'm new to jquery and unclear if I'm calling the function incorrectly? Or, why I'm not seeing the output of lines showing that I've entered the toggleRow function?
Related
I've got a table with a button inside a td, once I press the button it adds text to the td. I want to remove this text inside the td once i press the button again. note that this button is used multiple times in the table hence the class attribute.
Which method could I use to get this done?
This is my code:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<br>" + "test"); // td class="ReleaseTD"
}
// the code above this works
else {
$(this).text("Add");
$('.ReleaseTD').remove("<br>" + "test");
// this obviously is wrong but this is where i would like the correct code
};
});
You could create ID for text inside like this:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='textID'><br>" + "test</span>");
}
else {
$(this).text("Add");
$('#textID').remove();
};
});
Please try the following:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='txt_name'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#txt_name').remove();
};
});
Two ways:
1) Append your text into a span with a unique ID, and then delete this ID. For example, delete the ID with the largest number. Dumbest way would be to just store the latest ID in a global variable.
var global_last_appended_id = 0;
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
global_last_appended_id ++;
$('.ReleaseTD').append("<span id='appended-text-" + global_last_appended_id + "'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#appended-text-' + global_last_appended_id).remove();
global_last_appended_id--; //go one step back so next time we remove the previous paragraph
};
});
Update: after your edit I've added the ability to undo multiple times. Basically there is unlimited undo.
2) [lame and wrong] Save the previous .html() - the whole HTML code of your element - into a global variable; then restore the previous version of the text from the global variable when necessary.
I am working on a kendo Grid, on its databound event, I have called a function to check whether value in each of the row's second block is greater than first block. If true then I change color of texts inside by adding a class.
But, the problem is the added class gets away finally when I see on browser.
If there are two rows with error the first row that I am editing doesn't hold the class but the later ones holds that well.
dataBound: configureGridProperties,
Code for dataBound is
function configureGridProperties(e) {
try {
if (true) {
$('#grid .k-grid-content tr[role=row]').each(function (i) {
var sh = $(this).find('.sh').text();
var sm = $(this).find('.sm').text()
var eh = $(this).find('.eh').text()
var em = $(this).find('.em').text()
var startMin = parseInt(sh) * 60 + parseInt(sm);
var endMin = parseInt(eh) * 60 + parseInt(em);
if (startMin > endMin) {
showOutputExplicitly('Start time cannot be less than end time');
$(this).find('.sh, .sm,.eh,.em').addClass('timeError');
$('div.k-grid-pager').hide();
errorInTime = false;
}
else {
$(this).find('.sh, .sm,.eh,.em').removeClass('timeError');
if (!$('.timeError').length > 0) {
$('div.k-grid-pager').show();
hideErrorMsgSlow();
errorInTime = true;
}
}
});
}
return false;
} catch (e) {
}
pic for the situation . >
The second row that I just edited(start time 23) doesn't hold the colorChange class, but earlier ones hold that. Is there any other event that occurs after dataBound event?
It happens that when dataBound is called, the grid html elements are not rendered yet with the new data. I know that is strange, but I don't know other way than using setTimeout to make this work. So this may work:
dataBound: function(e) {
window.setTimeout(configureGridProperties.bind(this, e), 1);
}
Reference:
dataBound
bind()
Background: I have an external device (barcode reader) that sends information back to a tablet when the user scans something. I subscribe to that channel and I need the value to be inside the currently focused cell and write it there.
Bug: I can catch the subscription and write the value visually in the Input box, but it never reaches the JSON underneath.
I also tried $scope.$apply() but it did not change anything (maybe I used it wrong).
"Working" Plunker with the problem
$scope.randomClickOnStuff = function() {
// Here Randomely publish stuff with value so we can write it in specific field.
window.setTimeout(function() {
if (!$scope.stopMe) {
vm.objectOtSubscribeTo.publish(channelToUse, Date.now());
$scope.randomClickOnStuff();
} else {
// Stop the loop.
}
}, 1000);
};
var callbackCompleted = function(resultValue) {
// Important code Here
// Code to write in the input box here.
console.log(resultValue);
if (document.activeElement.localName == "input") {
// Option 1:
//--> Work Visually <-- but do not put the value inside the JSON.
document.activeElement.value = resultValue;
$scope.$apply();
// Option 2:
// http://stackoverflow.com/questions/11873627/angularjs-ng-model-binding-not-updating-when-changed-with-jquery
// Problem: The "document.activeElement.attributes['ng-model'].value" is not link with the scope, but with the ng-repeat row. So I have access to the Scope, but not the Row item.
//var binding = document.activeElement.attributes['ng-model'].value;
// Rule: I might not know where the Item is so I cannot do $scope.complexObject[row][binding]
} else {
console.log("not inside a Input box.");
}
};
vm.objectOtSubscribeTo.subscribe(channelToUse, callbackCompleted);
Thanks
One solution would be to keep track of the selected row and cell by setting them on focus of one of the cells
$scope.focusedRow = false;
$scope.focusedCell = false;
$scope.setFocused = (row, cell) => {
$scope.focusedRow = row;
$scope.focusedCell = cell;
};
/* In callback... */
if ($scope.focusedRow !== false && $scope.focusedCell !== false) {
$scope.$apply(
() => $scope.complexObject[$scope.focusedRow]
["cellInTheRow"][$scope.focusedCell] = resultValue
);
}
<input type="text" ng-model="row.cellInTheRow[key]"
ng-focus="setFocused(rowKey, key)" ng-blur="setFocused(false, false)">
Example: https://plnkr.co/edit/och5PoepJuRde0oONIjm?p=preview
I want to remove multi rows from table, and I have used the following code but does not work.
I'm use DataTables v1.10.9.
$('#del_Btn').on('click', function () {
// 'table' is the instance of table object
table.row('.selected').remove().draw(false);
}
Full code:
$('#del_MembersBtn').on('click', function () {
if (confirm('Do you want to remove the selected items ?') === true) {
var selRows = RemoveFromGroupTable.rows({selected: true}).data().pluck(0); // return an object contains selected rows
var selRowsLength = selRows.length;
var rows = new Array();
for (i = 0; i < selRowsLength; i++) {
rows.push(selRows[i]);
}
// remove the selected rows from table
RemoveFromGroupTable.rows('.selected').remove().draw(false);
var inputData = {};
inputData.selectdRows = rows;
inputData.submit = Math.floor(Math.random() * 10) + 1;
$.post(myProp.base_url + 'directory/class/method', inputData, function (outputData) {
if (outputData.submit == outputData.submit) {
tips();
}
}, 'json');
}
}
});
What can I do to remove multi selected rows ?
SOLUTION
Use rows to select multiple rows from the table as shown below
$('#del_Btn').on('click', function () {
table.rows('.selected').remove().draw(false);
}
If the button is located inside the table, it would be necessary to use delegated event handler as follows:
$('#example').on('click', '#del_btn', function () {
table.rows('.selected').remove().draw(false);
}
where example is your table ID.
DEMO
See this jsFiddle for code and demonstration.
i'm working with slickgrid and i'm quit new in slickgrid. i want to know is there any function through which i can get the complete info of all the cell to a specific row where user will click ??? also i want to get values before and after editing in the specific cell so that i can measure the change in the cell.
for getting the active cell (i.e. where user clicked) i'm using
ifkaar_scenarioConfigTable.onClick.subscribe(cellClicked);
and i'm checking where the cell is my desired cell(i.e. where user is allowed to do editing/modification) as following
function cellClicked(e) {
var cell = ifkaar_scenarioConfigTable.getCellFromEvent(e);
if (col[cell.cell].id == "orderqty") {
console.log("orderqty pressed");
}
}
this is working fine , i.e. when i click on any cell , it tell whether it is "orderqty" or not , but further i want to get its value and other cells' value in order to calculate the changes. I've searched but couldn't find any clear article (or i can't understood properly). any help will be highly appreciated. Thanks
the onClick event passes the row as an argument
Get the data item for a clicked row
function cellClicked(e, args) {
var item = grid.getDataItem(args.row);
}
Check if a click happened in a specific column
function cellClicked(e, args) {
if (args.cell == grid.getColumnIndex('orderqty')) {
console.log("orderqty pressed");
}
}
You could even pull this filtering functionality out into its own function and pass a callback when a click happens in that column
function forColumn(row, cell, columnID, fn) {
var cellNode = grid.getCellNode(row, cell);
var dataContext = grid.getDataItem(row);
if (cellNode && grid.getColumns()[cell].id === columnID) {
fn.call(this, cellNode, dataContext, row, cell);
}
}
function cellClicked(e, args) {
forColumn(args.row, args.cell, 'orderqty', function (cellNode, dataContext, row, cell) {
console.log("orderqty pressed");
});
}
Values before and after edit
To get the values of a cell before and after an edit you will need to handle this in the isValueChanged function in the editor for a column.
function cellClicked(e) {
var grid = ifkaar_scenarioConfigTable;
var cell = grid.getCellFromEvent(e);
var item = grid.getDataItem(cell.row); // all the data in the row
if (cell.cell == grid.getColumnIndex('orderqty')) {
console.log("orderqty pressed");
}
}
If you access grid from other control like . click button
var selectRow = gridInstance.getSelectedRows();
alert(gridInstance.getDataItem(selectRow).columnName)