Avoid display duplicate elements in table - javascript

So I saved some data in localStorage.
I get them back from localstorage to the table.
When I click on the button to enter new data, the data entered earlier is duplicated in the table. When I refresh the page, everything is fine.
$(document).ready(function() {
function save() {
list.forEach(function(item) {
var nameNode = document.createTextNode(item.name);
var surnameNode = document.createTextNode(item.surname);
var dataNode = document.createTextNode(item.data);
var nrNode = document.createTextNode(item.nr);
var tdName = document.createElement("td");
var tdSurname = document.createElement("td");
var tdData = document.createElement("td");
var tdNr = document.createElement("td");
tdName.appendChild(nameNode);
tdSurname.appendChild(surnameNode);
tdData.appendChild(dataNode);
tdNr.appendChild(nrNode);
var tr = document.createElement("tr");
tr.appendChild(tdName);
tr.appendChild(tdSurname);
tr.appendChild(tdData);
tr.appendChild(tdNr);
// download table and insert cells and rows
var table = document.getElementById("table");
table.appendChild(tr);
});
}
list = jQuery.parseJSON(localStorage.getItem("osoba") === null ? [] : localStorage.getItem("osoba"));
save();
$("#send").click(function() {
var osoba = {};
osoba["name"] = document.getElementById("name").value;
osoba["surname"] = document.getElementById("subname").value;
osoba["data"] = document.getElementById("date_bth").value;
osoba["nr"] = document.getElementById("numer_phone").value;
list.push(osoba);
localStorage.setItem("osoba", JSON.stringify(list));
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("date_bth").value = "";
document.getElementById("numer_phone").value = "";
save();
});
});
How to avoid duplication in the table without reloading the page?

When you save, you need to first clear the data already on the table or it will be added to it again when you call save. Here's how you do that:
$(document).ready(function(){
function save() {
$("#table tr").remove(); // <- this
list.forEach(function (item) {
var nameNode = document.createTextNode(item.name);
var surnameNode = document.createTextNode(item.surname);
var dataNode = document.createTextNode(item.data);
var nrNode = document.createTextNode(item.nr);
var tdName = document.createElement("td");
var tdSurname = document.createElement("td");
var tdData = document.createElement("td");
var tdNr = document.createElement("td");
tdName.appendChild(nameNode);
tdSurname.appendChild(surnameNode);
tdData.appendChild(dataNode);
tdNr.appendChild(nrNode);
var tr =document.createElement("tr");
tr.appendChild(tdName);
tr.appendChild(tdSurname);
tr.appendChild(tdData);
tr.appendChild(tdNr);
// download table and insert cells and rows
var table = document.getElementById("table");
table.appendChild(tr);
});
}
list = jQuery.parseJSON(localStorage.getItem("osoba") === null ? [] : localStorage.getItem("osoba"));
save();
$("#send").click(function(){
var osoba = {};
osoba["name"] = document.getElementById("name").value;
osoba["surname"] = document.getElementById("subname").value;
osoba["data"] = document.getElementById("date_bth").value;
osoba["nr"] = document.getElementById("numer_phone").value;
list.push(osoba);
localStorage.setItem("osoba",JSON.stringify(list));
document.getElementById("name").value="";
document.getElementById("surname").value="";
document.getElementById("date_bth").value="";
document.getElementById("numer_phone").value="";
save();
});
});

Related

How to get associative array elements and names. JS

Problem: Trying to get certain elements from a associative array, by using a loop. The loop is for multiple times i will go through. This associative array is associated to an array key. Ex: {eid0:{...},eid1:{...}}
It's to update a page with JS using DOM an no refresh. I've gone over StackOverflow and some other sites. I've looked in books. I can't seem to figure it out.
function display_oddsbet(id) {
var ds = document.getElementById("ds");
var tr = document.createElement("tr");
var td = document.createElement("td");
var tr0 = document.createElement("tr");
var tr1 = document.createElement("tr");
var tbl = document.createElement("table");
var tdsp = document.createElement("td");
var tdlg = document.createElement("td");
var tdloc = document.createElement("td");
var tda = document.createElement("td");
var tdh = document.createElement("td");
var tdsd = document.createElement("td");
var i;
var cnt= 0;
for (var s in id) {
var v = id[s];
for (var t in v) {
var k = v[t];
// for (var f in k) {
var ed = "eid" + cnt;
var i = v[ed];
cnt++;
console.log(i);
tr.classList = "eid" + cnt;
var a = i.awayteam_name;
var h = i['hometeam_name'];
var sd = i['startdate'];
var sport = i['sport_name'];
var league = i['league_name'];
var loc = i['location_name'];
tdsp.innerHTML = sport;
tdlg.innerHTML = league;
tdloc.innerHTML = loc;
tr0.appendChild(tdsp);
tr0.appendChild(tdloc);
tr0.appendChild(tdlg);
tbl.appendChild(tr0);
tda.innerHTML = a;
tdh.innerHTML = h;
tdsd.innerHTML = sd;
tr1.appendChild(tdsd);
tr1.appendChild(tda);
tr1.appendChild(tdh);
tbl.appendChild(tr1);
tr.appendChild(tbl);
// left
if (i['oddsbet'] == "1") {
td.innerHTML = "1";
td.style = "oddsbet";
tr.appendChild(td);
}
// 2 is on right
if (i['oddsbet'] == "2") {
td.innerHTML = "2";
td.classList = "oddsbet";
tr.appendChild(td);
}
// middle
else {
td.innerHTML = i['oddsbet'];
td.classList = "oddsbet";
tr.appendChild(td);
}
ds.appendChild(tr);
// }
}
}
return;
}
I get nothing doing this. I need to get i['awayteam_name']; and the rest from an API.
Don't ever forget. Garbage in Garbage out..
function display_oddsbet(id) {
var ds = document.getElementById("ds");
var tr = document.createElement("tr");
var td = document.createElement("td");
var tr0 = document.createElement("tr");
var tr1 = document.createElement("tr");
var tbl = document.createElement("table");
var tdsp = document.createElement("td");
var tdlg = document.createElement("td");
var tdloc = document.createElement("td");
var tda = document.createElement("td");
var tdh = document.createElement("td");
var tdsd = document.createElement("td");
Object.keys(id).forEach(function(key, index) {
var j = this[key];
Object.keys(j).forEach(function(key, index) {
//console.log(this[index]);
var ed = "eid" + cnt;
//var i = v[ed];
cnt++;
console.log(j[key]);
tr.classList = "eid" + cnt;
var a = j[key].awayteam_name;
var h = j[key]['hometeam_name'];
var sd = j[key]['startdate'];
var sport = j[key]['sport_name'];
var league = j[key]['league_name'];
var loc = j[key]['location_name'];
tdsp.innerHTML = sport;
tdlg.innerHTML = league;
tdloc.innerHTML = loc;
tr0.appendChild(tdsp);
tr0.appendChild(tdloc);
tr0.appendChild(tdlg);
tbl.appendChild(tr0);
tda.innerHTML = a;
tdh.innerHTML = h;
tdsd.innerHTML = sd;
tr1.appendChild(tdsd);
tr1.appendChild(tda);
tr1.appendChild(tdh);
tbl.appendChild(tr1);
tr.appendChild(tbl);
// left
if (j[key].oddsbet == "1") {
td.innerHTML = "1";
td.style = "oddsbet";
tr.appendChild(td);
}
// 2 is on right
if (j[key].oddsbet == "2") {
td.innerHTML = "2";
td.classList = "oddsbet";
tr.appendChild(td);
}
// middle
else {
td.innerHTML = j[key].oddsbet;
td.classList = "oddsbet";
tr.appendChild(td);
}
ds.appendChild(tr);
// }
}, j);
}, id);
return;
}

Search and match CSV file values with javascript

I've uploaded a CSV-file to an HTML page via javascript. The CSV rows are: name and email-address, e.g. rambo,rambo#rambo.com.
How to SEARCH the 'name' from these loaded CSV-file?
Also, one of the data is an email-address and I want to send a mail to that email-address. Is that value retrieved to a variable?
My code to search each elements:
function Search() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for(var j = 0; j < cells.length; j++)
{
var cell = row.insertCell(-1);
// cell.innerHTML = cells[j];
// Here repeated checkboxes:
var radio = document.createElement('input');
radio.type = 'checkbox';
radio.name = 'check';
}
var ser=document.getElementById("texts");
if(cells[i].indexOf(ser))
{
alert("matches");
cell.innerHTML = cells[i];
}
else
{
alert("unmatches");
}
var cell = row.insertCell(-1);
cell.appendChild(radio);
//cell.appendChild(button);
}
var button = document.createElement('button');
button.textContent = 'Send';
cell.appendChild(button);
button.onclick = function(){ alert();};
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
}
}
}
Ad search: indexOf() is your friend here. This should give you a figure:
var table = $('#your-table'),
searchstring = 'your-searchstring';
searchstring.toLowerCase();
for (var i = 0, cell; cell = table.cells[i]; i++) {
if (cell.indexOf(searchstring)) {
// I don't know what you want to do with the search-results...
// ..but you can do it here.
}
}
Ad email-address: you can add the address to a variable in your CSV-import:
var cells = rows[i].split(","),
address = cells[1];
I'd suggest making an array addresses and fill it each row.

How to add updated object information back into a specific index in an array of objects? (Javascript)

I have a practice app that is supposed to accept new information and put the information into an array of objects. It also has the option to edit specific data in the array. Everything works perfectly until I try and re-insert the new information back to where the old information was stored inside the array. The problem is occurring in the editObj function. I removed all the bad code I knew existed and left what I know works.
//HTML elements
var table = document.querySelector('#list');
var main = document.querySelector('#main');
var form = document.querySelector('#form');
var userInput = document.querySelector('#userInput');
var addBtn = document.querySelector('#add');
var saveBtn = document.querySelector('#save');
//Object array
var Assignments = [ ];
//main function
var mainView = function() {
table.innerHTML = '';
for(i = 0; i < Assignments.length; i++){
//elements
var row = document.createElement('tr');
var data = document.createElement('td');
var data2 = document.createElement('td');
var data3 = document.createElement('td');
var edit = document.createElement('td');
var remove = document.createElement('td');
var editBtn = document.createElement('button');
var deleteBtn = document.createElement('button');
//rendering
data.innerHTML = Assignments[i].name;
data2.innerHTML = Assignments[i].possible;
data3.innerHTML = Assignments[i].earned;
//innerText
editBtn.innerText = "Edit";
deleteBtn.innerText = "Delete";
//set attributes
editBtn.setAttribute('index',i);
deleteBtn.setAttribute('index',i);
//appending
edit.appendChild(editBtn);
remove.appendChild(deleteBtn);
row.appendChild(data);
row.appendChild(data2);
row.appendChild(data3);
row.appendChild(edit);
row.appendChild(remove);
table.appendChild(row);
//event listeners
editBtn.addEventListener('click', editObj);
deleteBtn.addEventListener('click', deleteObj);
//unhide table
main.style.display = '';
}
};
//add form
var addObj = function() {
main.style.display = 'none';
form.style.display = '';
};
var saveObj = function(e) {
e.preventDefault();
var itmObj = {};
var name = 'name';
var pP = 'possible';
var pE = 'earned';
itmObj[name] = userInput.name.value;
itmObj[pP] = userInput.pP.value;
itmObj[pE] = userInput.pE.value;
Assignments.push(itmObj);
console.log(Assignments);
form.style.display = 'none';
mainView();
};
//editing functions
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
newSaveBtn.style.display = '';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
};
//delete
var deleteObj = function(e) {
var removing = e.currentTarget.getAttribute('index');
Assignments.splice(removing, 1);
mainView();
};
//event listeners
addBtn.addEventListener('click', addObj);
userInput.addEventListener('submit', saveObj);
Assuming nothing is wrong with the current code... How do I get the new updated information back to the previous indexed value?
This was one of the ways that I tried and the eventListener will not fire on the new button:
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
var editBtn = document.createElement('button');
editBtn.innerText = 'Save New';
form.appendChild(editBtn);
editBtn.addEventListener('click', editTest);
//test editing
var editTest = function(e){
console.log(editing);
var newObj = {};
var newName = 'name';
var newpP = 'possible';
var newpE = 'earned';
newObj[newName] = userInput.name.value;
newObj[newpP] = userInput.pP.value;
newObj[newpE] = userInput.pE.value;
Assignments.splice(editing, 0, newObj);
form.style.display = 'none';
form.removeChild(editBtn);
saveBtn.style.display = '';
mainView();
};
};
Ah! Fixed it. Turns out the editObj and editTest functions needed to be combined. Here is the working code:
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
var editBtn = document.createElement('button');
editBtn.innerText = 'Save New';
form.appendChild(editBtn);
editBtn.addEventListener('click', function(e){
console.log(editing);
var newObj = {};
var newName = 'name';
var newpP = 'possible';
var newpE = 'earned';
newObj[newName] = userInput.name.value;
newObj[newpP] = userInput.pP.value;
newObj[newpE] = userInput.pE.value;
Assignments.splice(editing, 0, newObj);
form.style.display = 'none';
form.removeChild(editBtn);
saveBtn.style.display = '';
mainView();
});

TypeError: tableObj.appendChild is not a function

var oTable;
$(document).ready(function() {
loadSubMenus();
});
function loadSubMenus() {
var resultStringX = $.ajax({
type : "POST",
url : "getSubMenuList",
dataType : 'text',
async : false
}).responseText;
resultStringX = $.trim(resultStringX);
var o = JSON.parse(resultStringX);
var idArray = new Array();
var nameArray = new Array();
idArray = o.result.subMenuId;
nameArray = o.result.subMenuName;
var tableObj = $("#tableId").val();
var colCount = 0;
var trObj = document.createElement("tr");
for (var i = 0; i < idArray.length; i++) {
var tdObj = document.createElement("td");
var inputElem = document.createElement("input");
inputElem.type = "checkbox";
inputElem.setAttribute("id", "id_"+i);
inputElem.setAttribute("value", idArray[i]);
inputElem.style.marginTop = "-1px";
var spanObj = document.createElement("span");
spanObj.innerHTML = nameArray[i];
tdObj.appendChild(inputElem);
tdObj.appendChild(spanObj);
trObj.appendChild(tdObj);
colCount++;
if (colCount == 5) {
tableObj.appendChild(trObj);
trObj = "";
trObj = document.createElement("tr");
colCount = 0;
}
if (idArray.length < 5) {
if ((idArray.length - 1) == i) {
tableObj.appendChild(trObj);
}
}
}
if(idArray.length/5>0){
tableObj.appendChild(trObj);
}
document.getElementById("subMenuCount").value=idArray.length;
}
am not getting output..
i want to load menu n sub-menu from the database
what is error am nt able to get pls help me
how to solve this.
what i have to do..
what is the error
in another jsp page i created "tableid" so there i defined td
tableObj is not a DOM element. It is the value of $("#tableId").val(). Probably you need to create it also as a DOM element:
var tableObj = document.createElement("table");
...

HTML table is rendered in one line

I'm trying to generate a table dynamically using a userscript.
var divWrap = document.createElement('div');
divWrap.style.fontFamily = "sans-serif";
divWrap.style.width = "100%";
var spanTitle = document.createElement('span');
spanTitle.style.marginRight = "auto";
spanTitle.style.marginLeft = "auto";
spanTitle.style.fontSize = "1.5em";
spanTitle.innerHTML = "Countdown";
divWrap.appendChild(spanTitle);
var createTable = document.createElement('table');
createTable.style.marginLeft = "auto";
createTable.style.marginRight = "auto";
createTable.style.width = "50%";
createTable.id = "cdn_table"
divWrap.appendChild(createTable);
createTable.appendChild(addRow("test", "12d"));
createTable.appendChild(addRow("test2", "24h"));
mainDiv.getElementsByTagName('span')[0].appendChild(divWrap);
function addRow(rName, rValue) {
console.log(rName + ": " + rValue);
var row = document.createElement('tr');
var tName = document.createElement('td');
tName.innerHTML = rName;
var tValue = document.createElement('td');
tValue.innerHTML = rValue;
row.appendChild(tName);
row.appendChild(tValue);
return row;
}
The problem is that all elements are rendered in one line like this: http://i.imgur.com/MjMtdDg.png
Is there some css value I'm missing? Or something else? I want to insert simple title and table in that thumbnail with Scriptish in Firefox..
Tables have their own interface for adding rows/cells.
var t = document.createElement("table");
var r = t.insertRow(-1);
var c = r.insertCell(-1);
c.innerHTML = "Foo";
c = r.insertCell(-1);
c.innerHTML = "Bar";
document.body.appendChild(t);
http://jsfiddle.net/tQWm8/1/

Categories