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.
Related
In below code I am trying to create two HTML dynamic tables, but it doesn't work.
One table with ID "Table" and another one with ID "Tabled".
<script type="text/javascript">
function Upload() {
const columns = [0, 3] // represents allowed column 1 and 3 in index form
const dccolumns = [0, 3] // represents allowed column 1 and 3 in index form
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");
table.id = 'table'
var tabledc = document.createElement("tabled");
tabled.id = 'tabled'
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
// ignore columns that are not allowed
if (!columns.includes(j)) {
continue
}
var rc = cells[j];
if (rc == "SUMMARY") {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
alert(rc);
}
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
var alld = document.getElementById("alld");
alld.innerHTML = "";
alld.appendChild(tabled);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
When I run above code it just updates table in "Table", but not in "Tabled". I am not sure what wrong I am doing here.
Thanks
I am using ReactJS and I am creating a button "remove" in a method called showData() and appending it to a row in a table of people.
I am setting its attribute onclick to my method removePerson() implemented in the same class of the method showData().
This is all good until I click on the button "remove" - then an error shows:
ReferenceError: removePerson() is not defined at HTMLButtonElement.onclick
This is my code:
showData() {
let localStoragePersons = JSON.parse(localStorage.getItem("personsForms"));
persons = localStoragePersons !== null ? localStoragePersons : [];
let table = document.getElementById('editableTable');
let x = table.rows.length;
while (--x) {
table.deleteRow(x);
}
let i = 0;
for (i = 0; i < persons.length; i++) {
let row = table.insertRow();
let firstNameCell = row.insertCell(0);
let lastNameCell = row.insertCell(1);
let birthdayCell = row.insertCell(2);
let salaryCell = row.insertCell(3);
let choclatesCell = row.insertCell(4);
let genderCell = row.insertCell(5);
let workTypeCell = row.insertCell(6);
let hobbiesCell = row.insertCell(7);
let descriptionCell = row.insertCell(8);
let colorCell = row.insertCell(9);
firstNameCell.innerHTML = persons[i].firstName;
lastNameCell.innerHTML = persons[i].lastName;
birthdayCell.innerHTML = persons[i].birthday;
salaryCell.innerHTML = persons[i].salary;
choclatesCell.innerHTML = persons[i].Choclates;
genderCell.innerHTML = persons[i].Gender;
workTypeCell.innerHTML = persons[i].workType;
hobbiesCell.innerHTML = persons[i].Hobbies;
descriptionCell.innerHTML = persons[i].Description;
colorCell.innerHTML = persons[i].favoriteColor;
colorCell.style.backgroundColor = persons[i].favoriteColor;
let h = persons[i].ID;
let removeButton = document.createElement('button');
removeButton.setAttribute('onclick', 'removePerson(' + h + ')')
removeButton.innerHTML = 'Remove';
row.appendChild(removeButton);
}
}
I tried to change the code
removeButton.setAttribute('onclick', 'removePerson(' + h + ')');
to
removeButton.onclick = this.removePerson(h);
but everyTime the "showData()" method runs this method "removePerson()" run also and i don't want this to happen.
removePerson(ID) {
alert(ID);
let table = document.getElementById('editableTable');
if (persons.length === 1) {
table.deleteRow(1);
persons.pop();
localStorage.setItem("personsForms", JSON.stringify(persons));
}
let target;
let i;
for (i = 0; i < persons.length; i++) {
if (persons[i].ID === ID) {
target = persons[i].firstName;
persons.splice(i, 1); break;
}
}
for (i = 1; i < table.rows.length; ++i) {
let x = table.rows[i];
if (x.cells[0].innerHTML === target) {
table.deleteRow(i); break;
}
}
let temp = [];
let j = 0;
for (i = 0; i < persons.length; ++i) {
if (persons[i] !== null) {
temp[j++] = persons[i];
}
}
persons = temp;
localStorage.clear();
localStorage.setItem("personsForms", JSON.stringify(persons));
this.showData();
}
When you set a variable to some value, the value is computed first.
Hence, when you write removeButton.onclick = this.removePerson(h); the right side of the equation is evaluated first.
You can wrap it with a fat-arrow function, so that the function that will be called upon user click would be the function that calls this.removePerson(h). This way its value is a lambda function, and not the actual value of this.removePerson(h):
removeButton.onclick = () => this.removePerson(h);
This is my code
data = [{
name: 'Yemen',
code: 'YE'
},
{
name: 'Zambia',
code: 'ZM'
},
{
name: 'Zimbabwe',
code: 'ZW'
}
];
function addKeyValue(obj, key, data) {
obj[key] = data;
}
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "key";
checkbox.id = "id";
newinfo = data.map(function(person) {
return addKeyValue(person, 'checkbox', (checkbox)); });
var columnHeadings = Object.keys(data[0]);
var columnCount = columnHeadings.length;
var rowCount = data.length;
var table = document.createElement('table');
document.getElementById("data-list").appendChild(table);
var header = table.createTHead();
var row = header.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement('th');
headerCell.innerText = columnHeadings[i].toUpperCase();
row.appendChild(headerCell);
}
var tBody = document.createElement('tbody');
table.appendChild(tBody);
for (var i = 0; i < rowCount; i++) { // each row
var checkbox = document.createElement('input');
row = tBody.insertRow(-1);
for (var j = 0; j < columnCount; j++) { // each column
var cell = row.insertCell(-1);
cell.setAttribute('data-label', columnHeadings[j].toUpperCase());
var obj = data[i];
cell.innerText = obj[columnHeadings[j]];
}
}
In a tabular format I do have to get checkboxes with the json data. So firstly I have defined my json and then I have append checkboxes for each row.I am planning to add check boxes in every json object. But in my final output it is giving [object HTMLInputElement] instead of a checkbox.
You are adding the element object to your newinfo array, if you want the html for it you need to add it to the dom which it looks like you want to do at some point later in your code, to do this you would for example do document.body.appendChild(checkbox) if you wanted to add the checkbox to body.
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();
});
});
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");
...