How to display delete message in correct table row? - javascript

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);
}();
}

Related

Javascript deleting cookies with an HTML table

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);
}

Read a hard coded csv file and iterate through each entry to detect empty values

I have written a script for iMacro that reads a CSV file to extract numerous login details in order for passwords to be updated. The majority of these login details then also need to be updated on a second website, but in order to do so I need to be able to determine which sites have login details for the second site, and if they do, then run the second part of the iMacro script.
The CSV file I am using is laid out like so;
USERNAME 1 HEADER, PASSWORD 1 HEADER, USERNAME 2 HEADER, PASSWORD 2 HEADER
username1.1, password1.1, username1.2, password1.2
username2.1, password2.1, username2.2, password2.2
username3.1, password3.1, , ,
username4.1, password4.1, username4.2, password4.2
A loop would be used to process one row at a time, with a if statement inside to determine whether or not a empty/null value is present. If the second username or password are empty/null then the second part of the iMacro script would be skipped and the loop incremented.
I've never really used Javascript before, but I've have a bit of a look around and found jQuery-CSV, which looks like it's what I need but I cannot for the life of me get it to work. I also found this, which goes into detail about how to input a file, but it doesn't say how to hardcode it to a local file.
Any help on this would be greatly appreciated.
Thanks!
Here you go
HTML
<textarea id="csv"></textarea>
<button id="run">Run</button>
<div id="result"></div>
JS
$("#run").click(function(){
var result = $.csv.toArrays($("#csv").val());
empty = "";
html = "<table>";
for(i = 0; i < result.length; i++){
html += "<tr>";
for(j = 0; j < result[i].length; j++){
html +="<td>"+result[i][j]+"</td>";
if(result[i][j].trim() == ""){
empty += "cell "+i+" "+j+" is empty";
empty += "<br />";
}
}
html += "</tr>";
}
$("#result").html(html);
$("#result").append(empty);
});
http://jsfiddle.net/4J8Jb/
EDIT:
and to read the csv from a file you can use $.get like so
$.get('/path/to/file.txt',function(data) {
if (data == "ON") {
var result = $.csv.toArrays(data);
....
....
....
} else {
//there is an error reading the file
}
});

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.

Message always appears in first row?

I have a delete function within a function where if the user clicks on the "Delete" button, it displays a message stating that a file has been deleted. The code which does this is below:
$("#imagemsg").html(data);
But the problem is that let's say that I have 4 table rows and I delete a file in the 3rd row, the message should be displayed in the 3rd row only but instead it is displayed in the first row. Another example is that let's say that I have 8 table rows and I delete a file in the 6th row, the message should be displayed in the 6th row only but instead it is displayed in the first row.
Why is the message that is suppose to appear after a file is deleted is always displayed in the first row and not within the row the file has been deleted from?
Below is full code:
var counter = 0;
counter++;
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span id="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 id="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 the deleteimage.php script where the delete message is retrieved from:
<?php
$image_file_name = $_GET["imagefilename"];
echo "$image_file_name was Deleted";
unlink("ImagesFilesFolder/$image_file_name");
?>
The problem seems to be this:
.done(function(data) {
$("#imagemsg" + counter).html(data);
You set counter like this
var counter = 0;
counter++;
But you never seem to refer to the variable again. In any case, this variable is global - the command above will always target the ID with the current number of the counter, so it will not target the tr corresponding to the clicked button.
Since you use
$(this).parent().remove();
I assume that the parent is the tr concerned? In this case you could use a class instead of an ID 'imagemsg' and then do
$(this).parent().find(".imagemsg").html(data);
This would target the message inside the same row of the button.

how to display message in correct row and not all rows?

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 file 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").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.
So my question is what do I need to add to $(".imagemsg").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 = '';
if (success == 1){
result = '<span class="imagemsg">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');
$(this).parent().remove();
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg").html(data);
});
});
return true;
}
Pass the relevant element to the callback function. You already have $(this), so you can probably get the right row from that and put it in a variable, then access it in the callback to put the result in the right place.

Categories