javascript row index update after deleting a row - javascript

i'm learning JavaScript and have this assignment where I must build a table where i enter content. Every row must get an index number. And when this works you must be able to input the row number and delete this.
So far, so good.
BUT when i inputted multible rows and deleted the 3rd of 5 rows. And i saw that the row index numbers go from 1, 2, 4, 5. So it doesnt update. Now i want to fix that.. but how?!
I cant think of a way to only call uppon the 1st number of every row..
I hope you can help me..
The link to my project(sorry in advance, i am dutch!):
https://jsfiddle.net/Burner/kaqsgra1/
My loops for inputting the rownumber:
function addContent(){
for(i = 0; i < f.length; i++){
newData[i] = f.elements[i].value;
}
var newRow = contenttable.insertRow();
for (var i = 0; i< 4; i++){
newData[0] = contenttable.rows.length - 1;
var newCel = newRow .insertCell(i);
newCel.innerHTML = newData[i];
}
}
And when deleting a number i call this function:
function deleteNumber(){
var numRows = contenttable.rows.length - 1;
if(deleteNr.value == ""){
alert("Voer svp een nummer in!");
return false;
}
if(deleteNr.value > numRows){
alert("Dit rijnummer bestaat niet ");
return false;
}
document.getElementById("uitvoertabel").deleteRow(deleteNr.value);
}

In your deleteNumber function, renumber your rows after the selected row is deleted.
for (var i = 0; i< uitvoertabel.rows.length; i++){
uitvoertabel.rows[i].cells[0].innerHTML = i;
}
JSFiddle

Related

Strange behaviour in the if statement

I have a piece of code that is meant to hide table elements depending on given array. I am running loops to compare innerText of one of the cells and the given array.
However, my if statement is statement is acting weird, once i set the operator to === the operation is successful and table rows that match the array are hidden. But i need my if to hide the elements that are not a part of the array, so naturally I set my operator to !== but once i do it it just executes anyway and of course hides all of the elements in the table.
Any idea why this is happening here is the code:
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
var courseNames1 = [td1.innerText];
var diff = _.difference(soretedArray, courseNames1)
console.log(diff);
for (var i = 0; i < rowss.length; i++) {
for (var j = 0; j < diff.length; j++) {
if (td1[i].innerText === diff[j]) { // if i set the logic operator to !== it hides all of the elements rather the ones that don't match
console.log(rowss[i]);
rowss[i].style.display = "none";
break;
}
}
}
I added the code as I have understood your request: You want the negation of "contains" to hide the element. This is as complete as possible based on the information you gave.
var soretedArray = [];//initialized elsewhere
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
function tdContains(td) {
for(var j= 0 ; j< soretedArray.length; j++){
if(td.innerText === soretedArray[j]){
return true;
}
}
return false;
}
for(var i = 0 ; i < rowss.length; i++){
if(!tdContains(td1[i])) {
console.log(rowss[i]);
rowss[i].style.display= "none";
}
}

Delete rows in table built dynamically

I've been stuck on this stupid problem for a few days now. I guess it's not complicated but I might need someone's help...
Here is the thing: I start with an empty table in my html page. There is only the head with the name of the columns. Then, I get JSON data thanks to php, and I fill my table by creating a new row and new cells as follows:
for (var j = 0; j < jsonVal.length; j++){
var tr = table.insertRow(-1);
tr.insertCell(-1).innerHTML = "<img src=\"" + jsonVal[j].image + "\">";
tr.insertCell(-1).innerHTML = jsonVal[j].name;
tr.insertCell(-1).innerHTML = jsonVal[j].rating;
};
Now, all I want to do is to update this table according to some parameters (ordered by name or rating, only 5 lines etc...)
To do so, I want to delete all the rows I currently have to put with the new data. BUT I can't find a way to delete them. Here is my deleting code:
var currentTable = document.getElementsByTagName("table")[0];
var rowCount = currentTable.rows.length;
for(var i = 1; i < rowCount; i++){
currentTable.deleteRow(i);
}
I get the following error:
IndexSizeError: Index or size is negative or greater than the allowed amount
Is that the correct way to do it?
PS: sorry for such a long explanation.
My bad, I only needed to change i to 1 in my for loop as follows:
var currentTable = document.getElementsByTagName("table")[0];
var rowCount = currentTable.rows.length;
for(var i = 1; i < rowCount; i++){
currentTable.deleteRow(1);
}

How do you use a script to delete a row off of a spreadsheet that is linked to a form?

I have this script that does several things with data once it is entered into a google form, but I need to make sue that when two entrants have the exact same name that it deletes the previous entry entirely.
function formChanger() {
var doc = DocumentApp.openById('THIS WAS MY ID');
var body = doc.getBody();
var date = body.getListItems();
var dates = [];
for(var i = 0; i<date.length;i++)
{
dates.push(date[i].getText());
}
var form = FormApp.openById('THIS WAS MY ID');
var items = form.getItems();
var ss = SpreadsheetApp.openById("THIS WAS MY ID");
Logger.log(ss.getName());
var sheet = ss.getSheets()[0];
var values = sheet.getSheetValues(2, 4, sheet.getLastRow() , 1);
Logger.log(values);
var names = sheet.getSheetValues(2, 2, sheet.getLastRow(), 1);
var item = items[2].asMultipleChoiceItem();
var choices = item.getChoices()
for(var i=names.length; i>-1; i--){
for(var j=names.length; j>-1; j--){
if(names[i]==names[j] && i != j)
sheet.deleteRow(i);
}
}
var h = -1;
var j = -1;
var k = -1;
var l = -1;
for(var o = 0; o<values.length; o++){
if(choices[0].getValue().equals(values[o].toString()))
h++;
if(choices[1].getValue().equals(values[o].toString()))
j++;
if(choices[2].getValue().equals(values[o].toString()))
k++;
if(choices[3].getValue().equals(values[o].toString()))
l++;
}
if(h>3)
dates.splice(0,1);
if(j>3)
dates.splice(1, 1);
if(k>3)
dates.splice(2, 1);
if(l>3)
dates.splice(3, 1);
emptyDocument();
Logger.log(h);
Logger.log(j);
Logger.log(k);
Logger.log(l);
item.setChoices([
item.createChoice(dates[0]),
item.createChoice(dates[1]),
item.createChoice(dates[2]),
item.createChoice(dates[3])
]);
for(var i = 0; i<dates.length; i++)
body.appendListItem(dates[i]);
Logger.log(doc.getName()+" Contains:");
Logger.log(dates);
}
Yes the code is a mess, and I'm sure that it could be done a better way, but the important part is that I could be able to delete the line of information that is repeated. The compiler will not allow me to do this because the Spread Sheet is linked to the form. is there a way around this?
The following attempts at deletion are blocked in sheets receiving form data:
deletion of columns with form data
deletion of the row with form questions - that is, row 1
Other rows can be deleted at will. This behavior is exactly the same for scripts as it is for user actions.
Your script attempts to delete row 1 because it's buggy. I quote the relevant part:
var names = sheet.getSheetValues(2, 2, sheet.getLastRow(), 1);
for(var i=names.length; i>-1; i++){
for(var j=names.length; j>-1; j++){
if(names[i]==names[j] && i != j)
sheet.deleteRow(i);
What row is names[i] in? It's in row i+2, because i=0 corresponds to row 2. Yet, you attempt to delete row numbered i, two rows above the intended one.
Besides, i>-1; i++ is absurd; you want i-- there.
Here is a simple script that deletes row with duplicates; it's tested with my form responses. It traverses the contents of "Form Responses 1" sheet from bottom to top; if two rows have the same value in column C, the older one gets deleted. I do take care not to attempt deletion of row 1.
(The reason to do this in bottom-up order is to avoid dealing with rows that moved up because others were deleted.)
function deleteDupes() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form Responses 1');
var values = sheet.getDataRange().getValues();
for (var i = values.length - 1; i > 1; i--) {
if (values[i][2] == values[i-1][2]) {
sheet.deleteRow(i);
}
}
}

removing empty rows from an array in javascript

I have an array with empty rows,I have the field "codeOperation" to test if a row is empty or not,this is my table:
The client should fill the table whith data and left the rest of rows empty, what I want is when the client click on the "ADD" boutton only the data will be send and the emoty rows will be deleted.
this is my code:
//function to send the Data
$scope.updateGamme= function(gamme) {
gamme.listElementGammeOf = $scope.finalOperationsList;
$scope.DeleteEmptyRows(gamme.listElementGammeOf);
$http
.put(
baseUrl +
"/gamme/update",
gamme)
.success(
function(gammeModifiee) {
//send the Data and update
.....
}); }
//delete the empty rows
$scope.DeleteEmptyRows = function(listelements){
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i, 1);
}
What I get as a result with this code, is that per example I get 5 items, my code will remove the rows 3 and 4 the row 2 is not deleted
Is there any problem with my code? Please help me find it.
Thanks for help
Looks like
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i, 1);
}
should be
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i--, 1);
}
When you iterate and remove items from an array, you should decrement your index not to miss an item after the index shift due to removing.
Try splicing in reverse order. i.e remove rows from the last one.
I haven't tried your code but it must work.
$scope.DeleteEmptyRows = function(listelements){
for (var i = listelements.length-1; i >=0; i--) {
if (listelements[i].operationCode == "") {
listelements.splice(i, 1);
}
}
}
The example I tried is...
var array = ["1","2","","",""];
for(var i=array.length-1;i>=0;i--)
{
if(array[i]=="")
array.splice(i,1);
}

Hightlight differences between items in table row

I'm trying to add to a HTML table a feature that highlights all those values that, compared to others, are different. Comparison is made row by row.
With great effort I managed to achieve the following JQuery/Javascrit code. I'm pretty sure this is not an efficient/elegant/fast way to do it but it's the only way I work it out.
The HTML table is quite big and complex so it's hard to publish it here.
The issue I'm encountering is that the script works fine out of a loop, but it hangs if I put it inside a FOR - LOOP and I don't understand why.
var numRows = $('.ctable tbody tr').length, numCols = $('.ctable tbody tr:first th').length, v, undefined;
var values = new Array(numRows);
var noDuplicates = new Array(numCols);
var result = new Array(numCols);
for (i = 1; i = numRows; i++) {
// Get a row and copy into an array the values of each VISIBLE cell
$(".ctable tbody tr:eq(" + i + ") td.values:visible").each(function(){
v = $(this).text();
values.push(v.trim());
});
// Remove from the array the 'undefined' values
values = values.filter(function(item){
return item !== undefined;
});
// Push into new array duplicate values
noDuplicates = return_duplicates(values);
// Compare the two arrays and get the differences (uses underscore.js)
result = _.difference(values, noDuplicates);
// This is a 'highlight' plugin and you may pass to it an array
$(".ctable tbody tr:eq(" + i + ") td.values:visible").highlight(values);
}
function return_duplicates(arr) {
var len=arr.length, out=[], counts={};
for (var i=0;i<len;i++) {
var item = arr[i];
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
}
for (var item in counts) {
if(counts[item] > 1)
out.push(item);
}
return out;
}
Try
for (i = 1; i < numRows; i++) {
instead of
for (i = 1; i = numRows; i++) {

Categories

Resources