Why my selecting data only show the last data? - javascript

why i cannot select the first data and the second data when i tested using console.log
This is the table:
var ref = firebase.database().ref("recommendations");
ref.on("value", function(snapshot) {
// console.log(snapshot.val());
var recommendations = snapshot.val();
var keys = Object.keys(recommendations);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var title = recommendations[k].title;
var link = recommendations[k].link;
var presenter = recommendations[k].presenter;
// document.getElementById('title').innerHTML = title;
// document.getElementById('presenter').innerHTML = presenter;
// document.getElementById('link').innerHTML = link;
var table = document.getElementById("data");
var tr = document.createElement('tr');
var td1 = tr.appendChild(document.createElement('td'));
var td2= tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
var tdEdit = tr.appendChild(document.createElement('td'));
td1.innerHTML = title;
td2.innerHTML = presenter;
td3.innerHTML = link;
tdEdit.innerHTML = "<button id='"+k+"' class='btn btn-default edit'>Edit</button>";
table.appendChild(tr);
}
$(document).ready(function() {
$(".edit").on("click", function(){
console.log(k);
})
});
});

The issue is that you log k which is a reference to inside the loop. So the loop go's key0 key1 key2 and stays key2 because thats the last value of k.
Use something like:
$(document).ready(function() {
$(".edit").on("click", function(){
// From the button perspective this references the Native element.
console.log(this.id); // or $(this).attr("id")
})
});

Related

I want to set information to localstorage

playlist = [];
//저장
function save() {
localStorage.setItem("playlist",JSON.stringify(playlist));
}
// 리스트 생성
$('td#btn-add-row').click(function() {
// id 구하기
var list_num = 1;
for(var i=1; i <= 100; i++ )
{
if ( $('#basic tr td:nth-child(1)').hasClass(String(i)) == false )
{
list_num = i; break;
}
}
// 추가
const tbody = document.getElementById('my-tbody');
const tr = document.createElement("tr");
tr.id = list_num;
const td1 = document.createElement("td");
td1.className = list_num;
td1.setAttribute("style", "cursor:pointer");
const td2 = document.createElement("td");
td2.innerText = "음악 "+list_num;
const td3 = document.createElement("td");
td3.innerHTML = "<input type='text' name='tb'>";
const td4 = document.createElement("td");
td4.innerHTML = "<input type='text'>";
tbody.appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
const data = {
url:$("#my-tbody > tr:nth-child(" + list_num + ")> td> input").val(),
name:$("#my-tbody > tr:nth-child(" + list_num + ")> td:nth-child(4)> input").val(),
id:list_num
}
playlist.push(data);
save();
// 동적 테이블
$("#basic").tableDnD();
});
I wish that URL, name, id are stored in a local storage according to the id value of tr. However, this code produces strange results in localstorage. The problem is that the URL and name are not saved. What should I do?
The reference of a value does not magically keep on updating. So you need to add event listeners to keep updating it. So easiest thing to do is add event listeners to the inputs and update the array of objects.
Below is the basic idea. (note: StackOverflow blocks local storage so I commented it out.)
// const playlist = localStorage.playlist ? JSON.parse(localStorage.playlist) : [];
const playlist = [];
const tableTbody = document.querySelector("#myTable tbody");
for (let i = 0; i < 10; i++) {
// either get the current value from localstorage or create new record
playlist[i] = playlist[i] || {
id: i,
url: '',
name: ''
};
const currentItem = playlist[i]
//create the table row
const tr = document.createElement("tr");
tr.dataset.id = currentItem.id;
// create the id cell
const tdId = document.createElement("td");
tdId.textContent = i + 1;
// create the url cell
const tdUrl = document.createElement("td");
const inputUrl = document.createElement("input");
inputUrl.type = "text";
inputUrl.name = 'url';
inputUrl.value = currentItem.url;
tdUrl.append(inputUrl);
// create the name cell
const tdName = document.createElement("td");
const inputName = document.createElement("input");
inputName.type = "text";
inputName.name = 'name';
inputName.value = currentItem.name;
tdName.append(inputName);
// add the cells to the row
tr.append(tdId);
tr.append(tdUrl);
tr.append(tdName);
// add the row to the table
tableTbody.append(tr);
}
tableTbody.addEventListener("input", function (event) {
// see what triggered the input event
const input = event.target;
// find the row so we know what record to update
const rowId = input.closest("tr").dataset("id");
// what field to update
const field = input.name;
// update the record
playlist[rowId][field] = input.value.trim();
// update local storage
// localStorage.playlist = JSON.stringify(playlist);
});
<table id="myTable">
<thead>
<tr>
<th>ID</th><th>url</th><th>name</th>
</tr>
</thead>
<tbody></tbody>
</table>

how to remove duplicating values in rows

Is possible to remove duplicate values on html while updating in my firebase?
Js codes:
const tempRef = firebase.database().ref('Group1');
tempRef.on('value',gotData)
function gotData(data){
var nn= 0;
var G=data.val();
var keys=Object.keys(G);
for (var i = 0; i< keys.length; i++){
var k =keys[i];
var First_name = G[k].Info.First_name;
var value = G[k].value;
var tbody= document.getElementById('tbody1');
var trow= document.createElement('tr');
trow.className = 'rowing';
var td1= document.createElement('td');
var td2= document.createElement('td');
var td3= document.createElement('td');
td1.innerHTML= ++nn;
td2.innerHTML= First_name;
td3.innerHTML= value;
trow.appendChild(td1);trow.appendChild(td2);trow.appendChild(td3);
tbody.appendChild(trow);
}
}
You can try this:
const tempRef = firebase.database().ref('Group1');
tempRef.on('value',gotData)
function gotData(data){
var nn= 0;
var G=data.val();
var keys=Object.keys(G);
let uniqueNames = {}
for (var i = 0; i< keys.length; i++){
var k =keys[i];
var First_name = G[k].Info.First_name;
if(!uniqueNames[First_name]){
uniqueNames = {...uniqueNames, [First_name]:true}
var value = G[k].value;
var tbody= document.getElementById('tbody1');
var trow= document.createElement('tr');
trow.className = 'rowing';
var td1= document.createElement('td');
var td2= document.createElement('td');
var td3= document.createElement('td');
td1.innerHTML= ++nn;
td2.innerHTML= First_name;
td3.innerHTML= value;
trow.appendChild(td1);trow.appendChild(td2);trow.appendChild(td3);
tbody.appendChild(trow);
}
}
}

Javascript generated table - How to update other cells in a row when a number input value in this row changes

I am facing a problem for this day I am creating a pop-up cart with a table, I create an array with
ID | NAME | QUANTITY | PRICE
then I generate the table from this array with javascript.My problem is I want to be able to update the price and the total when I change the quantity for a specific item line (= quantity in the table row). This should work for all generated table rows.
This is my javascript code:
var cartCount = 0;
var Total = 0;
var id = 1;
var labels = ['Name', 'Quantity', 'Price'];
var items;
var cartElement = document.getElementById('cartDisplay');
var counterElement = document.getElementById('counterDisplay');
function cartClick(name, quantity, price) {
const x = {
id: id,
name: name,
quantity: quantity,
price: price
};
if (Obj.some(e => e.name === x.name)) {
console.log('already there');
} else {
Obj.push(x);
cartCount = cartCount + 1;
Total = Total + x.price;
id = id +1;
buildTable(labels, Obj, document.getElementById('modalBODY'));
items = Obj;
console.log(items);
}
CheckCart(cartCount);
console.log(cartCount);
}
function CheckCart(counter) {
if (counter > 0) {
cartElement.style.display = "block";
counterElement.innerHTML = counter;
} else {
cartElement.style.display = "none";
}
}
function buildTable(labels, objects, container) {
container.innerHTML = '';
var table = document.createElement('table');
// class table
table.classList.add("cartTable");
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var theadTr = document.createElement('tr');
for (var i = 0; i < labels.length; i++) {
var theadTh = document.createElement('th');
theadTh.classList.add("cartTh");
theadTh.setAttribute("colSpan", "2");
theadTh.style.padding = '12px';
theadTh.innerHTML = labels[i];
theadTr.appendChild(theadTh);
}
thead.appendChild(theadTr);
table.appendChild(thead);
for (j = 0; j < objects.length; j++) {
var tbodyTr = document.createElement('tr');
for (k = 0; k < labels.length; k++) {
var tbodyTd = document.createElement('td');
tbodyTd.classList.add("cartTd");
tbodyTd.setAttribute("colSpan", "2");
tbodyTd.style.padding = '12px';
if (labels[k] === "Quantity") {
var qinput = document.createElement('input');
qinput.setAttribute("type", "number");
qinput.setAttribute("min", "0");
qinput.setAttribute("max", "10");
qinput.setAttribute("id", "quantityInput");
qinput.setAttribute("value", objects[j][labels[k].toLowerCase()]);
tbodyTd.appendChild(qinput);
} else {
tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
}
tbodyTr.appendChild(tbodyTd);
}
tbody.appendChild(tbodyTr);
}
table.appendChild(tbody);
var tfoot = document.createElement('tfoot');
var footTr = document.createElement('tr');
var footTh = document.createElement('th');
var footTd = document.createElement('td');
footTd.setAttribute("id", "totalElement")
tbodyTd.setAttribute("colSpan", "3");
footTh.setAttribute("colSpan", "4");
footTd.innerHTML = Total;
footTh.innerHTML = 'TOTAL';
footTd.classList.add("cartTd");
footTd.classList.add("footerTable");
footTh.classList.add("cartTh");
footTr.appendChild(footTh);
footTr.appendChild(footTd);
tfoot.appendChild(footTr);
table.appendChild(tfoot);
container.appendChild(table);
var beforeText = document.createElement("p");
beforeText.style.marginTop = '5px';
beforeText.innerHTML = "Requests";
container.appendChild(beforeText);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.style.width = '100%';
input.style.padding = '6px';
input.setAttribute("placeholder", "No onion, no tomato...");
container.appendChild(input);
}
I solved a similar problem by creating a rowid and when the user clicks into the row I check for changes. Here the main idea
tableRow.setAttribute("id", "row" + idTable + "_" + tableRow.rowIndex); // for easy handling and selecting rows
tableRow.addEventListener("click", function(){ ... here check for what ever change});
You could also go for a specific change in just one cell, so attach the eventlistener to each quantity cell and read the new value, validate and update other fields then
qinput.addEventListener("change", function(){ ... here check for what ever the change triggers });
EDIT fortheOP:
A generic example for adding an event listener to a tablerow this marks the selected table line red (class table-danger) and removes the colour from allother previous selected lines:
tableRow.addEventListener("click", function(){
tRowData = [];
if(this.classList.contains("table-danger")) {
this.classList.remove("table-danger");
return;
} else {
var nodeParent = this.parentNode;
var trows= nodeParent.getElementsByTagName("tr");
for(var i = 0; i < trows.length;i++) {
trows[i].classList.remove("table-danger");
}
this.classList.add("table-danger");
var cells = this.getElementsByTagName("td");
for ( i = 0; i < cells.length; i++) {
tRowData.push(cells[i].innerHTML); // e.g.: Here you could place your update routine
}
tRowData.push(this.getAttribute("id"));
tRowData.push(this.rowIndex);
return tRowData;
}
});

Make table using object

I'm making a table but using only Javascript. I did the table already and it shows right on console, but I can't make it visible on the page. I tried appendChild() and insertBefore() and it doesn't work, and also can't make the URL clickable.
Here is my code:
var companies = [
{
id: 1,
name: 'Google',
link: 'http://google.com/'
},
{
id: 2,
name: 'Microsoft',
link: 'http://microsoft.com/'
},
{
id: 3,
name: 'Apple',
link: 'http://apple.com'
}
];
var tbl = document.createElement('table');
var input = document.getElementById('input');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_link = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_link.textContent = "link";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_link);
thead.appendChild(tr_head);
for(var i = 0; i < companies.length; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_link = document.createElement("td");
// var id = companies[i].id;
// var name = companies[i].name;
// var link = companies[i].link;
td_id.textContent = companies[i].id;
td_name.textContent = companies[i].name;
td_link.textContent = companies[i].link;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_link);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
// input.appendChild(tbl);
Do you write the output to the document? Else it will just remain in the script.
Like this:
document.body.appendChild(tbl);
Not the best way, but it's a way...
var input = document.getElementById("input");
var rows = "";
for(var i = 0; i < companies.length; i++) {
rows += "<tr><td>"+companies[i].id+"</td>"
+ "<td><a href='"+companies[i].link+"'>"+companies[i].name+"</a></td></tr>"
}
var table = "<table>"+rows+"</table>";
input.innerHTML = table;

Delete the row you click on (Javascript dynamic table)

I want to delete a row from a table, I am using Javascript.
I am dynamically creating table rows and in the last cell I have delete button so how to make it delete the row?
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
this is the function for creating my table rows
function addItem()
{
document.getElementById('add').onclick=function()
{
var myTable = document.getElementById('tbody');
var newRow = document.createElement('tr');
//var element1 = document.createElement("input");
//element1.type = "checkbox";
//newRow.appendChild(element1);
var newData1 = document.createElement('td');
newData1.innerHTML = document.getElementById('desc').value;
var newData2 = document.createElement('td');
newData2.innerHTML = document.getElementById('taskPriority').value;
var newData3 = document.createElement('td');
newData3.innerHTML = document.getElementById('taskDue').value;
myTable.appendChild(newRow);
newRow.appendChild(newData1);
newRow.appendChild(newData2);
newRow.appendChild(newData3);
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
}
}
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
try this code here is fiddle
alternatively try
//delete the table row
$(document).on('click', '#del', function(){
$(this).parents('tr').remove();
});
}); //del is the id of the delete block
one pure javascript approach
function deleteRowUI(btndel) {
var table=document.getElementById('filterTableBody');
if (typeof(btndel) == "object") {
p=btndel.parentNode.parentNode;
p.parentNode.removeChild(p);
var oTable = document.getElementById('filterTableBody');
//gets rows of table
var rowLength = oTable.rows.length;
for (var i = 1; i < rowLength; i++){
var oCells = oTable.rows.item(i).cells;
//gets cells of current row
var cellLength = oCells.length-1;
for(var j = 0; j < cellLength; j++){
oCells.item(j).innerHTML = "";
break;
}
break;
}
} else {
return false;
}
}
if you want to temporary hidden it you can do:
this.parentNode.style.display='none';
in mind that the exclusion button is in a td.
But if you want to really delete it from the html and the database:
you need to make the same as above and a extra call to a function of php/plsqlwathever to delete from de db, i recommend using ajax to call it.
http://www.w3schools.com/ajax/default.asp
uses jQuery remove method to do it.
By the id attribute :
$("#id here").remove();
By the class attribute :
$(".class name here").remove();
I hope I've helped a little...

Categories

Resources