JavaScript delete-function does not work (absolute Newbie) - javascript

First off: sorry for that awful Code. I am an absolute beginner and this is my very first JS code ever and I had to code it under time-pressure (not good).
The task was to code a guest book. I have a function that creates a new div per entry and appends it to the last one (this part works well).
var lastid = 2;
function eintragen() {
...
var divC = document.createElement('div');
var ident='item'+lastid;
divC.innerHTML = '<table id="'+ident+'" class="eintrag center">
<tr><td>Name:</td><td>'+name2+'</td></tr><tr>
<td>Email:</td><td>'+email2+'</td></tr>
<tr><td>Eintrag</td><td>'+nachricht2+'</td></tr>
<tr><td></td><td><button class="buttonklein"value="loeschen"
***onclick="loeschen('+ident+')"***
>Eintrag löschen</button></td></t></table><hr>';
**divC.setAttribute('id',ident);**
var add = document.getElementById('item1');
add.appendChild(divC);
lastid+=1;
...
}
I tried do highlight the relevant part. As you can see, I gave the id to the divC twice, because after testing, I figured out, that it did not work in the "divC.innerHTML"-segment.
Every entry has an own delete-button, which should - you guess it - delete that associated entry.After clicking the button, the function starts, but then nothing happens.
function loeschen(itemid) {
var sitem = document.getElementById(itemid);
sitem.parentNode.removeChild(sitem);
}
I guess, since assigning the ID to the divC did not work in the "divC.innerHTML" part, it also does not work to assign it as a parameter to the "onclick" -attribute.
If I replace itemid with something concrete like 'item4' in the loeschen-function, it does delete entry number 4, so I guess the mistake is in the divc.innerHTML-part.
Question: Where did I go wrong? Any wrong '' oder ""? How can i give every button the current itemid? everything worked fine for the other variables like name oder email, so I have absolutely no clue.
Thanks so much in advance and sorry for my bad style. I will work on this in the future.

User Teemu found the answer super fast and was a great help.
It was indeed bad syntax in the divC.innerHTML-segment.
This does the job:
divC.innerHTML = `<table id="${ident}" class="eintrag center">
<tr><td>Name:</td><td>${name2}</td></tr><tr>
<td>Email:</td><td>'+email2+'</td></tr>
<tr><td>Eintrag</td><td>${nachricht2}</td></tr>
<tr><td></td><td><button class="buttonklein" value="loeschen"
onclick="loeschen('${ident}')">Eintrag löschen</button>
</td></t></table><hr>`;

Related

Apps Script extremely slow or endlessly "Preparing for execution..."

I have written a very simple code on my Google Sheets file. This is the purpose:
Save some cells values from StaticSheet (all the Copyxxx) that need to be copied in DynamicSheet.
Get the value of one specific cell inserted by the user manually.
Enter a While loop useful only to increase an indicator and get the number of the row where I want to copy those values previously saved.
Copy those values on this row but different columns.
The problem is that it seems that most of the time it does not even run the script after I told it to do so.
What is funny is that sometimes it works, super slowly, but it works for like a couple of minutes. And after it stops working again.
Could you please tell me what am I missing here please?
function Copy_Static_on_Dynamic() {
var app = SpreadsheetApp;
var ss = app.openById("xxxxyy--------yyzzzz")
var StaticSheet = ss.getSheetByName("DEAT Price");
var DynamicSheet = ss.getSheetByName("DEAT Price + TEST");
var CopySKU = StaticSheet.getRange(5,1,40);
var CopyPrices = StaticSheet.getRange(5,3,40,4);
var CopyUsage = StaticSheet.getRange(5,8,40);
var Week_1 = StaticSheet.getRange(2,4).getValues();
var i = 1;
Logger.clear();
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
{
Logger.log(i);
i+=1;
}
CopySKU.copyTo(DynamicSheet.getRange(i,4,40));
CopyPrices.copyTo(DynamicSheet.getRange(i,6,40,4));
CopyUsage.copyTo(DynamicSheet.getRange(i,11,40));
}
If you see the "Preparing for Execution" message in the Apps Script editor, you can reload the browser window and run the function again. The program will likely go away.
So I think I have solved it.
As Serge insas was saying I had my script running on the background, I found it out on the "Execution" section, where you can also interrupt them.
After I discover it I kept testing, and I saw that the while loop needed almost 2 seconds to check the condition every time, making the script incredibly long.
So instead of:
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
... I have created a variable declared previously such as:
var WeekLOOP = DynamicSheet.getRange(i,3).getValues();
while(WeekLOOP != Week_1) { --- }
... and now the script needs few milliseconds to run the condition. I don't have enough technical knowledge to say if this was the only issue, but is what apparently solved my problem.
Thanks to all for the support! Will come back if I need any further help :)
As was mentioned by Amit Agarwal, to solve the error message mentioned on the question, refresh the web browser tab.
Regarding the code,
On
var Week_1 = StaticSheet.getRange(2,4).getValues();
and
DynamicSheet.getRange(i,3).getValues()
instead of getValues you should use getValue because your code are referring to single cell cells otherwise you will be getting 2D arrays instead of scalar values.
The use of while should be made very carefully to avoid functions running endlessly. You could add some "safeguard" like the following
var max_iterations = 100 // Edit this
while(DynamicSheet.getRange(i,3).getValue() != Week_1 && i <= max_iterations) {

Problems with onclick / calculating a sum

Let me start by saying, that while I have some programming experiencing (some basic C from a college class and I once wrote a FORTRAN programm in college for a professor), I am utterly new to JS and beginning to get a bit frustrated.
For some reason, even after reading tutorials and watching several YouTube videos on objects, I seem unable to wrap my head around it. I understand the fundamentals and have no problems doing very basic stuff, like writing a loop that prints out increments on a HTML site, but every time I try something practical, I am completely at a loss.
Here is my current problem: I have created this HTML site that generates a shopping list. Basically, when I click on one of the buttons next to an item name, it adds that item to the list in the middle of my screen. Thanks to Google I found a piece of JavaScript code which, through try and error, I managed to tweak for this purpose:
<!-- click this button to add the item-->
<button onclick="myFunction('ITEM1', 100)" class="sidebarbuttons" >ITEM1 </button>
/* Create a List one line at a time- */
<script>
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
So far, so good. Now I want to get the net price for all the items. Which means, When I click the button, I want a function to add the price of that item to a variable and then display that variable in a field with
document.getElementById("result").innerHTML = total_sum;
Here's my question: how, oh my god, how do I do this? I thought I could add the following:
function myfunction(x,y){
var sum = 0;
var sum+=y;
}
document.getElementById("result").innerHTML = 'sum';
Obviously, this doesn't work at all. Can you please give me some hints what I have to do to make this work?
First of all,
please consider to study JavaScript better, because it's a falsy easy programming language and it's very dangerous to copy&paste without knowing the language. It's quite normal to read a lot, watch a lot and don't know where to start, and it's the main reason because people hates JavaScript: because we don't know well JavaScript. So consider to read the book series "You Don't Know" by Kyle Simpson.
About your question. You can add a variable to storage the sum of your items and when you click to an item, you can add to it:
var total_sum = 0;
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
showResults(y);
}
function showResults(price){
total_sum += parseFloat(price)
document.getElementById("result").innerHTML = total_sum;
}
JSBIN
Let me know ;)
So you are on the right track. Picking up where you left off in your last code block, there are few things you will need to change.
//declare the variable outside of the function... otherwise it will only be available to you within that function.
var totalSum = 0;
// then within your function you will be able to successfully add to the global totalSum variable
function calculateSum(x){
totalSum += x;
// and lastly... set the innerHTML within the function... which should equal the variable totalSum
document.getElementById("result").innerHTML = totalSum;
}
Hope this helps.

Making a variable I can manipulate further

I'm relatively new to jQuery and need to perform some transformations on the following working code:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
})
The code returns the value of a radio button clicked in a tab id of #vari_1.
The problem is I then need to replace hyphens of the radio button value with spaces (duck-egg-blue to duck egg blue) and prepend an h2 heading. Chaining these appears to break my code.
I instead tried the below to make it into a variable so I can work with that on a new line, but couldn't get it to work. Can someone point me in the right direction please?
jQuery('#vari_1').click(function() {
var selected = [];
var cart1 = jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
var cart2 = ('<h2>My heading</h2>') + cart1;
return cart2;
})
It's driving me nuts! Thanks in advance.
It sure can seem daunting Utkanos, I'm yet to get a straight answer to a question after being a member for a good few years. All I seem to attract is ambiguity and politician style question dodging!
Anyway due to lack of a hint other than Ashkay's syntax error spot (not in my code sorry), I fixed it as such:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch').addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val().replace("-"," "))
.prepend('<div class="mystyle"><small>My Label:</small><br />')
.append('</div>')
.fadeIn('5000');
})
val().replace() prepend() and append() were all I was after.
Thanks for the reassurance anyway!

Can't use document.getElementById().innerHTML to rewrite the original html

I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.

proper coding with array.push

I've found some code on a site and been tinkering with it a little. It involves some functions to add and delete students (the add code is below) from an array - into a value field. I can't figure out why in tarnations we need this extra piece of code, however.
Here is the js code:
var students = ['Paulie', 'Nicole', 'Kevin', 'Mare'];
function addClick(){
var addRemove = document.getElementById('addRemoveStudent');
var studentsBox = document.getElementById('studentsBox')
students.push(addRemove.value);
addRemove.value = '';
studentsBox.value = students.join(', ');
}
My question is: Why do we need the addRemove.value = ''; line? I've tested it without that code and it still works fine. Is there a reason we need that?
I can send more code including the HTML but didn't what to overwhelm anyone with the volume.
Thanks so much in advance!
-Anthony
It's not necessary. I guess semantically it means to clear the addRemove box first before replacing the value.
It's optional, but it's simply to clear the text box so the user can enter a brand new value if they want to run the function again.
To clear the value of the addRemoveStudent ( I think it is a input type="text") Just for it, It is not needed in the array. Just to clear the value of that control.
Presumably addRemove is an input element. Setting the value property of an input element to an empty string '' means that the input is emptied: it will have no text in it.
My guess is that this function is run when a button is clicked, so it adds a new student to the array, updates the studentsBox field with the right data, and clears the input element so you can add more if the user wishes to do so.

Categories