Duplication of rows in Javascript Table - javascript

I am quite new to javascript and for some time now i cant figure a solution to a problem that i have on my own. The web application i am building is using javavascript and Firebase. I am creating a table that pulls some data from mysql and display them as a table in my website. The table consists of three columns ID,NAME, AND SURNAME.Along with that i am also creating a new column called Recipient that consists of buttons. The table looks like this:
I give a different value to each of the buttons, the value of each button is the number of the ID that is in the same row as the current button. For example the first button has a value = 2, the 3rd a value = 123. Al the buttons have an id = contact
The source code of the table is
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName`,`storagefolder` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table class=table table-condensed>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Recipient</th>
</tr>
</thead>";
while($record = mysql_fetch_array($clients)){
echo "<action=usersfiles.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<button value=".$record['ID']." id=contact>Folder Data</button>"." </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
When i click on a button from the table the application get the value of the corresponding button and store it in a variable, then it sends the variable to a function that will drug all the files from firebase database that are store in the folder with the same name as the variable, And then it will display them.
My firebase Database
So for example when I click on the button of the first column I will get the files that are stored in the folder with name 2 form firebase.database. The result of after I click the first button will be this:
My source code works fines as it gets the files from the corresponding folders from firebase.database. The problem that i have is when i dont refresh the page and i click a button again then the outpout will be the result of the previous button click plus the new one. For example if i dont refresh my page and i click the second button to get the files from the file from database with the name = 3 the outpout will be :
The outpout is a merging of all the results that i have oupouted so far. If i refresh my page and click on the second button now i will get the result i want which it is:
How can i edit my source code so the tables wont merge?
My source code is the follwing:
Source code of saving the value after button is clicked and passsing it to function:
var contactName; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contact"]').click(function() {
contactName = $(this).val(); //set var contactName to value of the pressed button
store(contactName);
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
Source code of function receiving the value and displays the corresponding file from firebase database:
function store(value){
var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref().child(`files/${value}/`);
var rowIndex = 1;
databaseRef.once('value',function(snapshot){
snapshot.forEach(function(childsnapshot) {
var childKey = childsnapshot.key;
var childData = childsnapshot.val();
//var urls = childData.url;
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var button = row.insertCell(2);
var itd = document.createElement('input');
itd.setAttribute("type","button");
itd.setAttribute("value","View");
itd.onclick=function () {
window.open(childData.url);
};
cellId.appendChild(document.createTextNode(childData.filename));
cellName.appendChild(document.createTextNode(childData.created));
button.appendChild(itd);
rowIndex = rowIndex+1;
//document.write(username);
})
});
}
Thanks in Regards

You only append data to the existing table, without ever removing existing rows in the table:
var row = tblUsers.insertRow(rowIndex);
You should make sure to remove all existing rows before adding the new one(s):
for (var i = tblUsers.rows.length; i >= 0; i--) {
tblUsers.deleteRow(i - 1);
}

Related

how to replace old table rows with new rows using javascript

I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});

Append a New Table Row (1 Row 2 Columns) on Google Apps Script

I'm trying to make an automation script that updates an existing Google Docs based on user responses from Google Form. so there are 3 questions (Name, University Number Identification or NIM in Bahasa, and Department or bidang), the department question used for categorizing each respondent.
So the goal is whenever a form is submitted, then the Docs is updated too. So I want to make the update make a new row with a cell that contains a template string that I already used in my script on the spreadsheets. But the problem is it only appends a single column for each row, however, that's not what I intended to have happened. I want it to update 1 row and 2 columns.
Screenshot Of the Google Form
Screenshot of the Google Docs Error
Screenshot of what I intended the Google Docs when it's updated to be
function appendTable(variabel){
var rangePSDI = body.findText(variabel);
var searchElement = body.findElement(DocumentApp.ElementType.TABLE, rangePSDI);
element = searchElement.getElement();
table = element.asTable();
table.appendTableRow().appendTableCell(variabel);
}
if (bidang == 'PSDI') {
body.replaceText('{{NamaPSDI}}', nama);
body.replaceText('{{NIMPSDI}}', nim);
appendTable("{{NamaPSDI}}");
appendTable("{{NIMPSDI}}");
return;
} else if (bidang == 'PSDM') {
body.replaceText('{{NamaPSDM}}', nama);
body.replaceText('{{NIMPSDM}}', nim);
appendTable("{{NamaPSDM}}");
appendTable("{{NIMPSDM}}");
return;
}
Think of the appendTableRow as <tr> in HTML where you have to set the cell using <td>or appendTableCell.
See Table Row element in HTML.
Try this:
Code:
function appendTable(){
var doc = DocumentApp.openById('someid');
var body = doc.getBody();
var tables = body.getTables();
var text = "PSDM";
tables.forEach(table => {
if(table.getCell(0,0).getText() == text){
table.replaceText("{{Nama"+text+"}}", "test nama"+text)
table.replaceText("{{NIM"+text+"}}", "test NIM"+text)
var tr = table.appendTableRow();
tr.appendTableCell("{{Nama"+text+"}}");
tr.appendTableCell("{{NIM"+text+"}}");
}
})
}
Before:
After:
PSDI
PSDM

acts_as_votable javascript html table

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.
I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.
I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?
Here is the dashboard.js:
var insertDest = function(dest) {
// Find a <table> element with id="myTable":
var table = document.getElementById("destTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var name_cell = row.insertCell(0);
var address_cell = row.insertCell(1);
// var delete_cell = row.insertCell(2);
var like_cell = row.insertCell(2);
like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
var like_count_cell = row.insertCell(3);
like_count_cell.innerHTML= 0;
// Add some text to the new cells:
name_cell.innerHTML = dest.name;
address_cell.innerHTML = dest.address;
// delete_cell.innerHTML = "<div class='del'>x</div>";
addMarker(dest.address,map);
};
var insertAllDest = function(trip){
var d = trip.destinations;
for (i in d){
insertDest(d[i]);
}
};
However, does this mean I need to write a 'attachLikeHandler' function
to deal with what happens when the like button is clicked?
Yes:
$(".like").on('click', function() {
$.ajax({
method: "PUT",
url: "/photos/" + $(this).attr("id"),
success: function(msg_from_server) {
alert(msg_from_server); //"Thanks for voting!" or "Sorry, you already voted!"
}
});
});
If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

Get selected value from externally created dropdownlist

I'm creating a dynamic menu that fetches dishes from a database and displays them to the user so he can add them to his order. Whenever I retrieve a row from the database I send it to my menuItems class so the columns can be read and the display format is created and inserted into a cell:
foreach (DataRow dr in drc){
//extract the dish data from the row into a cell
TableCell c1 = menuItem.makeItemCell(dr);
//display it
tr.Controls.Add(c1);
table1.Controls.Add(tr);
}
c1 will be a cell that has the dish information along with a quantity dropdownlist and an "add to order" button:
public static TableCell makeItemCell(DataRow dr)
{
TableCell tc = new TableCell();
Image img = new Image();
img.ImageUrl = (string)dr["img"];
tc.Controls.Add(img);
//rest of information adding is omitted for brevity
String myLiteral = "<p>" + "Name: " + (string)dr["NameofDish"] + "</br>";
tc.Controls.Add(new LiteralControl(myLiteral));
//add quantity label and dropdownlist populated with possible quantity values
Label lb = new Label();
lb.Text = "Quantity: ";
DropDownList ddl = new DropDownList();
for (int i = 0; i < 13; i++)
{
String t = i.ToString();
ddl.Items.Add(new ListItem(t, t));
}
//create the add to order button
Button btn = new Button();
btn.Text = "Add to order";
tc.Controls.Add(lb);
tc.Controls.Add(ddl);
tc.Controls.Add(btn);
return tc;
}
My problem is with handling the button click event. All my tries to bind it with an event handler (on the menuItems class or the codebehind itself) have failed. I could only manage to update the postbackURL of the button when it's created in the cell like this
btn.PostBackUrl = "./menu.aspx?dish=" + (string)dr["ID"] + "&quantity=" + ddl.SelectedValue;
But the .selectedvalue value is rendered when the cell is created hence is always 0
My question is this: how can I handle the button click event in a way that I can get hold of the dishID and the selected value.
((((I would prefer an event handling solution rather than querystrings if possible))))
Thank you!
EDIT:
My whole problem is that the cell and its components are created in the external class and sent back to my code. How do I access the dropdownlist variable from my codebehind if I don't have the element id or anything

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.

Categories