I have only started js recently, so i hope this makes sense..
I have made a simple dynamic form which starts with a table of 4 rows. After the heading row, the remaining 3 rows have +/- symbols which are to add or delete rows as necessary.
The add row functionality is currently working, however, even after assigning the correct class to the new row, the event listener wont work for the new buttons (even thought i have re-assigned the number of buttons within that class).
After adding the row, i re-assign btnAddRows and when logged to the console it is increasing with each row added. I can't figure out why it wont get captured in the for loop?
Thanks
//select elements on DOM
let btnAddRows = document.querySelectorAll('.btnADD');
let myTable = document.querySelector('#SecProp');
let myTableRows = document.querySelector('.tableRows');
for (let i = 0; i < btnAddRows.length; i++) {
btnAddRows[i].addEventListener('click', function () {
console.log(btnAddRows.length);
btnAddRows = document.querySelectorAll('.btnADD');
const rowNum = Number(btnAddRows[i].id.slice(6));
// console.log(rowNum);
// if (rowNum === myTableRows.length - 1) {
// addTableRow(rowNum);
// } else {
addTableRow(rowNum);
// }
btnAddRows = document.querySelectorAll('.btnADD');
myTable = document.querySelector('#SecProp');
myTableRows = document.querySelector('.tableRows');
});
}
const addTableRow = function (rowNum) {
//insert row into table
const addRw = myTable.insertRow(rowNum + 1);
const newRow = myTable.rows[rowNum + 1];
newRow.className = 'tableRows';
console.log(myTable.rows[rowNum + 1], typeof myTable.rows[rowNum + 1]);
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
const cell3 = newRow.insertCell(2);
const cell4 = newRow.insertCell(3);
const cell5 = newRow.insertCell(4);
cell1.className = 'column1';
cell2.className = 'coordsColumn';
cell3.className = 'coordsColumn';
cell4.className = 'buttons';
cell5.className = 'buttons';
cell1.innerHTML = `<td> ${rowNum + 1}</td>`;
cell2.innerHTML = '<td ><input type = "text" name="" value = ""/><td>';
cell3.innerHTML = '<td ><input type = "text" name="" value = ""/><td>';
cell4.innerHTML = `<td ><button class="btnADD btn btn-success" id="btnADD${
rowNum + 1
}"> + </button>`;
cell5.innerHTML = `<td ><button id="btnDEL${
rowNum + 1
}" class="btnDEL btn btn-success"> -</button>`;
};
Related
Is there a way to filter the data in column Q off my google sheet faster then reading line one by one. There is daily about 400+ lines it needs to scan through and I need to delete every row of data if the data in column Q is less than 1 right now watching it, it takes about 10+ minutes.
function UpdateLog() {
var returnSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('CancelRawData');
var rowCount = returnSheet.getLastRow();
for (i = rowCount; i > 0; i--) {
var rrCell = 'Q' + i;
var cell = returnSheet.getRange(rrCell).getValue();
if (cell < 1 ){
returnSheet.deleteRow(i);
}
}
{
SpreadsheetApp.getUi().alert("🎉 Congratulations, your data has been updated", SpreadsheetApp.getUi().ButtonSet.OK);
}
}
Try it this way:
function UpdateLog() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const vs = sh.getDataRange().getValues();
let d = 0;
vs.forEach((r, i) => {
if (!isNaN(r[16]) && r[16] < 1){
sh.deleteRow(i + 1 - d++);
}
});
}
This is a bit quicker
function UpdateLog() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const vs = sh.getDataRange().getValues().filter(r => !isNaN(r[16]) && r[16] < 1);
sh.clearContents();
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}
I have a for loop which is working on my google sheet but it takes around 5 minutes to filter through the 2100 rows of data. I have read about using filters and getting rid of the for loop all together but I'm fairly new to coding in Google Script and haven't been able to get my head around the syntax for this. Any advice greatly appreciated.
Code below:
function Inspect() {a
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
for (var i = 2; i <= lastRow; i++) {
var cell = srcSheet.getRange("A" + i);
var val = cell.getValue();
if (val == true) {
var srcRange = srcSheet.getRange("B" + i + ":I" + i);
var clrRange = srcSheet.getRange("A" + i);
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":H" + (tarRow+1));
var now = new Date();
var timeRange = tarSheet.getRange("I"+(tarRow+1));
timeRange.setValue(now);
srcRange.copyTo(tarRange);
clrRange.clear();
//tarRange.activate();
timeRange.offset(0, 1).activate();
}
}
};
Yes, to speed-up you will need to get all the values first and apply your logic to the obtained 2D-arrays instead of cells, at the end you will use setValues to update your sheet. I would go for something like this:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var srcLastRow = srcSheet.getLastRow();
var tarLastRow = tarSheet.getLastRow();
var srcArray = srcSheet.getRange(1,1,srcLastRow,9).getValues();//(A1:I(lastrow))
var tarArray = tarSheet.getRange(1,1,tarLastRow,9).getValues();//(A1:I(lastrow))
for (var i = 1; i < srcArray.length; i++) {
var val = srcArray[i][0];
if (val == true) {
var copyValues = srcArray[i].slice(1);//Get all elements from the row excluding first column (srcSheet.getRange("B" + i + ":I" + i);)
var now = new Date();
copyValues[8]=now;//set the time on column 9 (array starts at position 0!)
var tarNewLine = copyValues;
tarArray.push(tarNewLine);
//clear values on source (except column A):
for(var j=1;j<srcArray[i].length;j++){
srcArray[i][j]="";
}
}
}
tarSheet.clear();
tarSheet.getRange(1, 1,tarArray.length,tarArray[0].length).setValues(tarArray);
srcSheet.clear();
srcSheet.getRange(1, 1,srcArray.length,srcArray[0].length).setValues(srcArray);
};
You cannot get around a loop, but you should reduce the number of calls to the SpreadsheetApp to a minimum, see Apps Script Best Practices
It is not the for loop, but those calls that make your code slow. Instead, work with arrays as much as you can. Loops become of a problem if they are nested - this is also something you should avoid.
Sample how to perform most calls to SpreadsheetApp outside of the loop and work with arrays:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
var Acolumn = srcSheet.getRange("A2:A" + lastRow);
var Avalues = Acolumn.getValues();
var srcRange = srcSheet.getRange("B2:I" + lastRow);
var srcValues = srcRange.getValues();
var array = [];
var now = new Date();
for (var i = 0; i < lastRow-1; i++) {
var val = Avalues[i][0];
if (val == true) {
srcValues[i].push(now);
array.push(srcValues[i]);
var clrRange = Acolumn.getCell(i+1, 1);
clrRange.clear();
}
}
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
if(array.length!=0){
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":I" + (tarRow + array.length));
tarRange.setValues(array);
}
};
I have a problem, I like to show a select text values of a MultiSelect control on a tooltip.
I only can show the value(numeric) from MultiSelect, this is my code:
var multiselect = $("#combo_multi").data("kendoMultiSelect");
value2 = multiselect.value(); //show only numeric values ->14376, etc.
Show the numeric values together without spaces. ->14376
I like to show the text value, not the numeric value.
I think I have to use an array for show the text value, but I don´t know how do it.
If somebody have the response of this problem, I appreciate the solution. Thanks.
Maybe this could help you a bit
var multiselect = $("#combo_multi").data("kendoMultiSelect");
var value2 = multiselect.value();
var selectedValues = value2.split(",");
var multiSelectData = multiselect.dataSource.data();
for (var i = 0; i < multiSelectData.length; i++) {
var numberValue = multiSelectData[i].number;
for (var j = 0; j < selectedValues.length; j++) {
if (selectedValues[j] == numberValue) {
// here we get description for value
var desc = multiSelectData[i].description;
break;
}
}
}
Example other
$("#multiselect").kendoMultiSelect();
var multiselect = $("#CityTo").data("kendoMultiSelect");
var dataItem = multiselect.dataItems();
//***Debug
var CityArray = new Array();
CityArray = dataItem;
alert(JSON.stringify(CityArray));
//***End Debug
//**************** Applied example
var newHtml = "";
var item = dataItem;
$.each(item, function (index, item) {
newHtml += '<div class="panel panel-default" ><div class="panel-heading">' + item.City_Name + '</div><div class="panel-body">Panel Content</div></div>';
});
$("#CityCount").html(newHtml);
You can see the details "dataItem" using "item."
item.City_Name
I'm on a newer version of Kendo UI so possibly things have changed since you asked this. I'll give you an updated answer..
var multiselect = $("#combo_multi").data("kendoMultiSelect");
var selectedValues = multiselect.value();
var multiSelectData = multiselect.dataSource.data();
var count = selectedValues.length;
for (var i = 0; i < multiSelectData.length; i++) {
if (selectedValues.indexOf(multiSelectData[i].Value) >= 0 ) {
//found, do something
var selectedText = multiSelectData[i].Text;
count--;
}
if (count == 0) {
break;
}
}
I'm having trouble to select text in CKEditor(3.6). As we use plain text i dont know how to use correctly the range selectors.
HTML code of the CKEditor:
<body spellcheck="false" class="rf-ed-b" contenteditable="true">
<br>
Cross those that apply:<br>
<br>
<br>
[«dummy»] If he/she is tall<br>
<br>
[«dummy»] If he/she is a male<br>
<br>
[«dummy»] If he/shi is a minor<br>
<br>
Specialties:<br>
<br>
[«dummy»] «Write here the specialties if known»<br>
<br>
<br>
«You are now done with filling in this form»<br>
</body>
With the keys 'CRTL+N' I want to go to the next filleble spot:
«[label]»
I tried stuff like:
var editor = CKEDITOR.instances['MyEditor'];
var findString = '«';
var element = editor.document.getBody();
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + 5);
editor.getSelection().selectRanges([ranges[0]]);
}
Error:
Exception: Index or size is negative or greater than the allowed amount
While totally stripepd down it kinda works a bit:
var editor = CKEDITOR.instances['MyEditor'];
var ranges = editor.getSelection().getRanges();
var startIndex = 10;
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + 5);
editor.getSelection().selectRanges([ranges[0]]);
}
here it selects 5th till 10th char on first row.
I used the following sources:
example on Stackoverflow
Another stackoverflow example
CKEditor dom selection API
All solutions i can find work with html nodes.
How can set selection range on the '«' till next '»'
I've managed to solve this solution. Meanwhile i also upgraded CKeditor to 4.0.
This shouldnt have an impact on the solution.
It is a lot of code in JS.
On my keybinding i call the following JS function: getNextElement()
In this solution it also searches behind the cursor, this makes it possible to step through multiple find results.
Also the view gets scrolled to the next search result
var textNodes = [], scrollTo=0,ranges = [];
function getNextElement(){
var editor =null;
ranges = [];
// I dont know the ID of the editor, but i know there is only one the page
for(var i in CKEDITOR.instances){
editor = CKEDITOR.instances[i];
}
if(editor ==null){
return;
}
editor.focus();
var startRange = editor.getSelection().getRanges()[0];
var cursorData ="",cursorOffset=0,hasCursor = false;
if(startRange != null && startRange.endContainer.$.nodeType == CKEDITOR.NODE_TEXT){
cursorOffset = startRange.startOffset;
cursorData = startRange.endContainer.$.data;
hasCursor = true;
}
var element;
element = editor.document.getBody().getLast().getParent();
var selection = editor.getSelection();
// Recursively search for text nodes starting from root.
textNodes = [];
getTextNodes( element );
var foundElement = false;
foundElement = iterateEditor(editor,hasCursor,cursorData,cursorOffset);
if(!foundElement){
foundElement =iterateEditor(editor,false,"",0);
}
if(foundElement){
// Select the range with the first << >>.
selection.selectRanges( ranges );
jQuery(".cke_wysiwyg_frame").contents().scrollTop(scrollTo);
}
}
function iterateEditor(editor,hasCursor,cursorData,cursorOffset){
var foundElement = false;
var rowNr = 0;
var text, range;
var foundNode = false;
if(!hasCursor){
foundNode = true;
}
// Iterate over and inside the found text nodes. If some contains
// phrase "<< >>", create a range that selects this word.
for (var i = textNodes.length; i--; ) {
text = textNodes[ i ];
if ( text.type == CKEDITOR.NODE_ELEMENT && text.getName() == "br" ){
rowNr++;
} else if ( text.type == CKEDITOR.NODE_TEXT ) {
var sameNode = false;
if(text.$.data == cursorData){
foundNode = true;
sameNode = true;
}
if(foundNode){
var startIndex = -1;
var endIndex = 1;
if(sameNode){
// Check inside the already selected node if the text has multiple hits on the searchphrase
var indicesStart = getIndicesOf('\u00AB', text.getText());
var indicesEnd = getIndicesOf('\u00BB', text.getText());
for (var j = indicesStart.length; j--; ) {
if(indicesStart[j] > cursorOffset){
startIndex = indicesStart[j];
endIndex = indicesEnd[j];
}
}
} else{
startIndex = text.getText().indexOf( '\u00AB' );
endIndex = text.getText().indexOf( '\u00BB' );
}
if ( startIndex > -1 && (!sameNode || startIndex > cursorOffset)) {
range = editor.createRange();
range.setStart( text, startIndex );
foundElement = true;
// calculate the height the window should scroll to focus the selected element
scrollTo = (rowNr)*20;
}
if ( endIndex > -1 && foundElement ) {
range.setEnd( text, endIndex+1 );
ranges.push( range );
return true;
}
}
}
}
}
function getIndicesOf(searchStr, str) {
var startIndex = 0, searchStrLen = searchStr.length;
var index, indices = [];
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function getTextNodes( element ) {
var children = element.getChildren(), child;
for ( var i = children.count(); i--; ) {
child = children.getItem( i );
textNodes.push( child );
}
}
Do you guys know of any .net controls with 2 listboxes that can move items from left to right and vice versa?!
Like a dual listbox type of thing.
I have already looked at http://ajaxlistbox.codeplex.com/ it seems to be pretty sweet.
just want to know any suggestions.
Here's a way:
Make two ListBoxes, the first shows all available item, the second shows what the user chooses. You also need a TextBox to hold a copy of the chosen items, since it is not possible to retrieve ListBox items in C# if they were added via javascript. Make the TextBox hidden, so the user cannot accidentally mess up the items.
Click an item in the first listbox and it appears in the second "chosen" listbox. Click on chosen item in the second list and it disappears. You could alter this so items are removed from the first list after being chosen.
I call AddJavascript from my Page_Load method.
ListBoxFilteredProfiles is my first TextBox, ListBoxSelectedProfiles is the second.
private void AddJavascript()
{
// This javascript function adds the item selected in one listbox to another listbox.
// Duplicates are not allowed, items are inserted in alphabetical order.
string OnChangeProfileListBoxJavascript =
#"<script language=JavaScript>
<!--
function OnChangeSelectedProfiles()
{
var Target = document.getElementById('" + ListBoxSelectedProfiles.ID + #"');
var Source = document.getElementById('" + ListBoxFilteredProfiles.ID + #"');
var TB = document.getElementById('" + TextBoxProfiles .ID + #"');
if ((Source != null) && (Target != null)) {
var newOption = new Option(); // a new ListItem
newOption.text = Source.options[ Source.options.selectedIndex ].text;
newOption.value = Source.options[ Source.options.selectedIndex ].value;
var jj = 0;
for( jj = 0; jj < Target.options.length; ++jj ) {
if ( newOption.text == Target.options[ jj ].text ) { return true; } // don't add if already in the list
if ( newOption.text < Target.options[ jj ].text ) { break; } // add the new item at this position
}
for( var kk = Target.options.length; kk > jj; --kk ) { // bump the remaining list items up one position
var bumpItem = new Option();
bumpItem.text = Target.options[ kk-1 ].text; // copy the preceding item
bumpItem.value = Target.options[ kk-1 ].value;
Target.options[ kk ] = bumpItem;
}
Target.options[ jj ] = newOption; // Append the item in Target
if (TB != null) {
// Copy all the selected profiles into the hidden textbox. The C# codebehind gets the selections from the textbox because listbox values added via javascript are not accessible.
TB.value = '';
for( var jj= 0; jj < Target.options.length; ++jj ) { TB.value = TB.value + Target.options[ jj ].value + '\n'; }
}
}
}
// -->
</script> ";
// This javascript function removes an item from a listbox.
string OnChangeRemoveListBoxItemJavascript =
#"<script language=JavaScript>
<!--
function OnChangeRemoveProfile()
{
var Target = document.getElementById('" + ListBoxSelectedProfiles.ID + #"');
var TB = document.getElementById('" + TextBoxProfiles.ID + #"');
Target.remove( Target.options.selectedIndex );
TB.value = '';
// Copy all the selected profiles into the hidden textbox. The C# codebehind gets the selections from the textbox because listbox values added via javascript are not accessible.
for( var jj= 0; jj < Target.options.length; ++jj ) { TB.value = TB.value + Target.options[ jj ].value + '\n'; }
}
// -->
</script> ";
ClientScript.RegisterStartupScript( typeof(Page), "OnChangeSelectedProfiles", OnChangeProfileListBoxJavascript );
ClientScript.RegisterStartupScript( typeof(Page), "OnChangeRemoveProfile", OnChangeRemoveListBoxItemJavascript );
ListBoxFilteredProfiles.Attributes.Add("onchange", "OnChangeSelectedProfiles()" );
ListBoxSelectedProfiles.Attributes.Add("onchange", "OnChangeRemoveProfile()" );
}