Javascript deleting cookies with an HTML table - javascript

I was trying to make a code that when you introduce a table row (clicking on a button) it use the first cell from the row as name of a cookie. That's fine, at least atm.
My problem is that when i try to delete a row from that table I want to delete the cookie that is associated with that, not that hard, but i'm not really sure what am i doing wrong.
Thanks!
http://jsfiddle.net/roucher/d9h6onvr/
function borrarTR() {
document.getElementById("tablaPaseadores").deleteRow(0);
contador--;
var x = document.getElementById("tablaPaseadores").rows.length;
var celda = "celda" + x + "1";
alert(celda);
var cname = document.getElementById(celda).innerHTML;
alert(cname + "1");
deleteCookie(cname);
It dosent alert that last alert: "(cname + "1")" So I guess the problem is in celda, but celda returns the right value.
EDIT: Solved.
I had 2 errors: first and main one, if i try to get the id of something that has been already deleted, it will obviously return null.
And second, I should have realised also that the lenght in from [1-i] and I am working from [0-i-1] so i had to do this to solve both:
function borrarTR() {
var x = (document.getElementById("tablaPaseadores").rows.length)-1;
var celda = "celda" + x + "1";
var cname = document.getElementById(celda).innerHTML;
document.getElementById("tablaPaseadores").deleteRow(0);
contador--;
deleteCookie(cname);
}

Related

Having trouble triggering a Google spreadsheet function on Form Submission

I have created a Google form that is linked to a Google spreadsheet containing two sheets. I have also created a function in Google Scripts, called "handleFormSubmission", that when triggered (on submission of the linked form):
creates a variable containing the values of this submission from sheet one: var s0Row = s0.getRange("A"+(s0Last)+":J"+(s0Last)).getValues();
then, if a matching ID condition is met on both sheets, sets those values from sheet one into the appropriate range on sheet two: s1Row.setValues(s0Row);
There's probably a better way to do this, but for now the function works fine when run from Google Scripts and the form is returning submissions to sheet one.
The problem I'm having is getting this function to trigger when the linked form has been submitted. I've attempted to set this trigger up as you'll see in the screen shot below.
Code
function handleFormSubmission() {
var ss = SpreadsheetApp.openById("1FmArzo50IV2Wmykgsa89l_EARjzkiyeFDoPaCjGyBZM");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActive();
var s0 = sheet.getSheets()[0];
var s0Last = s0.getLastRow();
var s1 = sheet.getSheets()[1];
var s1Last = s1.getLastRow();
var s0Bid = s0.getRange(s0Last, 10).getValue();
var s0Row = s0.getRange("A"+(s0Last)+":J"+(s0Last)).getValues();
for (var i = 2; i < s1Last + 1; i++) {
var s1Bid = s1.getRange(i, 10).getValue();
var s1First = s1.getRange(i, 2).getValue();
var s1LastName = s1.getRange(i, 3).getValue();
var s1Row = s1.getRange("A"+(i)+":J"+(i));
if (s0Bid === s1Bid) {
Logger.log(i + " " + s1First + s1LastName);
Logger.log("s0: " + s0Bid);
Logger.log("s1: " + s1Bid);
Logger.log("Match!");
s1Row.setValues(s0Row);
Logger.log("----------------------");
break;
} else {
Logger.log(i + " " + s1First + s1LastName);
Logger.log("s0: " + s0Bid);
Logger.log("s1: " + s1Bid);
Logger.log("Nope...");
Logger.log("----------------------");
}
};
};`
Current Project's Triggers
It's definitely an event on the spreadsheet that you're intercepting, although that may seem counter-intuitive.
I had the same problem & solved it by deleting the trigger, creating a new version of the script, then recreating the trigger. Don't know why it works -- perhaps a GAppsScript expert could explain it to us.
Also, why not get your form submission values out of the event object? So, instead of hunting down the last row of sheet[0] (which could, in an extreme case, not be the submission you're looking for, but the next one), you can access the field you want from the event object using either of:
e.values (an array of the form values in the order they appear in the spreadsheet)
e.namedValues (a dictionary/hash of the form values)
I think the event should be "From form" not "From spreadsheet". That is because you are working on script editor opened from the spreadsheet. It populates when you open the script editor from the form and write the function in that editor. Hope that helps!

Dynamically adding rows to a form without resetting previous row

Hi this is a second part to an early question. I need to add rows to a form consisting of a selection box. Each row of the form is a type of "Room" in a house and the user has to be able to add as many rooms as needed. I have it all working however if you fill in the 2nd room and then add a 3rd room it resets the selection box to its default for the 2nd room. I can see why it is doing this i just cant think of how to change the function so it keeps your previous selections intact. Note: i have the 1st row for the 1st room written in the HTML then this function(below) is called from a button click and adds the extra rooms.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room')
var roomSelect = '<select name="level[]" id="levels"' + room_count + '/> ';
roomSelect += '<option>Basement</option>';
roomSelect += '<option>Lower Level</option>';
roomSelect += '<option>Main Floor</option>';
roomSelect += '<option>2nd Floor</option>';
roomSelect += '<option>3rd Floor</option></select>';
write.innerHTML += roomSelect;
room_count++;
}
Thanks for any help you can offer!
This is because of the magic of .innerHTML +=.
As you might have guessed, It's actually identical to div.innerHTML = div.innerHTML + moreHTML - So the browser resets the HTML of the div. Including any selection, obviously.
I'd recommend you used div.appendChild. It doesn't change previously loaded HTML, and so won't change the user's selection.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room');
var roomSelect = document.createElement('select'); // create select node
roomSelect.setAttribute("name", "level[]");
roomSelect.setAttribute("id", "levels" + room_count);
roomSelect.innerHTML = '<option>Basement</option>'+ //set the innerHTML (the options)
'<option>Lower Level</option>'+
'<option>Main Floor</option>'+
'<option>2nd Floor</option>'+
'<option>3rd Floor</option>'
write.appendChild(roomSelect); //append the child
room_count++;
}

Display summary of choices in JS

this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')

jQuery Error - Generating undefined

So I have a list of users registered on my site in 1 column, in the 2nd is their email address with a checkbox next to it. On this page a user can check the box (or multiples) and click a submit button. Once they do that it will generate a list of the emails semicolon separated.
My issue is after they hit submit the lists generates, but the first email address has "undefined" written right next to it.. so instead of saying "domain1#test.com; domain2#test.com" it reads "undefindeddomain1#test.com; domain2#test.com".
Here is my jQuery:
jQuery(document).ready(function() {
jQuery('#memberSubmit').click(function() {
var emailList;
jQuery('.email-members input:checked').each(function() {
var $this = jQuery(this);
emailList += $this.next('a').html() + "; ";
});
jQuery('.email-message').hide();
jQuery('.email-members').hide();
jQuery('.email-checks').hide();
jQuery('#memberSubmit').hide();
jQuery('.email-results a').attr('href', "mailto: " + emailList).fadeIn(2000);
jQuery('.email-results .email-list p').html(emailList).fadeIn(2000);
jQuery('.email-results h2').fadeIn(2000);
jQuery('.email-results p').fadeIn(2000);
jQuery('.email-list h2').fadeIn(2000);
//console.info('Emails: ' + emailList);
});
});
I think my error is on the line: emailList += $this.next('a').html() + "; ";
But I am not sure... any ideas?
Thanks!
Initialize the emailList the variable first, that means it doesn't start at undefined when you perform your first go around. Coincidently, when you're calling += for the first time, it's actually converting undefined to a string, thus meaning your string always starting with that.
var emailList = "";
Try replacing emailList's declaration with this code:
var emailList = "";
That's because emailList starts out as undefined if you don't initialize it. Therefore undefined + "this is a test" would turn out as undefinedthis is a test.

How to display delete message in correct table row?

Below is a function where it controls whatever happens after a file has finished uploading in its own table row. Each table row consists of a file input where the user can upload a file and then the name of the file is appended within it's own table row.
If the upload was successful then it displays a successful message, if upload was not successful then it displays a message stating there is an error. But I also have another function within the function where the user can delete a file by clicking on the "Delete" button. The only problem I have is with this line of code:
$(".imagemsg" + counter).html(data);
Let's say that I have 2 table rows, and I delete a file in the first row, the message within .imagemsg should only be displayed in the first row as that was the row the deletion occured, it shouldn't display the message in the first and second row.
Another example is that if I have 4 table rows and I delete the file in the third row, then the message should be displayed in the 3rd row as that is where the deletion has occured.
So my question is what do I need to add to $(".imagemsg" + counter).html(data); so that the message is only displayed within the row the deletion of the file occured and not in all .imagemsg which is in every row?
Below is full code:
function stopImageUpload(success, imagefilename){
var result = '';
var counter = 0;
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
BELOW IS HTML CODE:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='listImage' align='left'></p>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
I believe that your counter variable will always be 1. So, all your span.imagemsg1 are the same. This is why you get the message in every row. Set the counter outside the function to increment the counter.
I believe that will stop the behavior that you are seeing, but I would like to give a shout out to the other answers as they are giving good advice to cleaning this code up.
Frankly, you should never use unique identifier in the class. Why not use an id or a data-image-count attribute?
In your html code you'll need to add a unique identifier, I would suggest using id. This way when you try to reference the element to add the error message in, it will only find one element. Currently it's looking for the first occurrence of the element with class = "imagemsg". You'll need a way to loop through each "row" and make the id's "imagemgs1", "imagemsg2", etc...Hope it helps.
It would be helpful to be able to see the HTML. Also, I cannot see in your script what you do with the "result" value. At this stage, I personally don't think there is enough info to help satisfactorily you yet.
However, an issue you will undoubtedly see is with your "counter" variable. Maybe that is your problem - hard to tell without the detail I asked for above. Your jQuery.ajax call will complete at some point but the value of "counter" may not be the same as when you called the jQuery.ajax() method. This is because the "counter" variable is being declared in a different scope.
E.g. Look at the code below. It sort of demonstrates your problem with the counter variable. It may look like at the end of 5 seconds it will spit out the numbers from 1 to 10 but it won't. It will spit out the value "10" ten times.
var x = 0;
for (var i = 0; i < 10; i++)
{
x++;
setTimeout(function() { console.log(x); }, 5000);
}
This problem applies to your code as well. You can fix the above by copying the variable value in to a variable of your local scope. E.g.:
var x = 0;
for (var i = 0; i < 10; i++)
{
var newScope = function() {
x++;
var y = x;
setTimeout(function() { console.log(y); }, 5000);
}();
}

Categories