populate json data in tables - javascript

javascript code
$(function(){
$(".user").on("click",function(e){
e.preventDefault();
var email = $(this).data("email");
$.ajax({
data:{email:email},
type: "POST",
url: 'getUser_detail.php',
success: function(data) {
var data = JSON.parse(data);
for (var i = 0; i < data['basic'].length; i++) {
$('#inputs').append('<label>Email:</label><input type="text" readonly class="form-control-plaintext" value="' + data['basic'][i].email + '" name="email[]" size="15">');
$('#inputs').append('<label>Password:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Pass +'" name="pass[]" size="5">');
$('#inputs').append('<label>Status:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].status +'" name="pass[]" size="5">');
$('#inputs').append('<label>Acc. Address:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Accno +'" name="pass[]" size="44">');
$('#inputs').append('<label>Balance:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].bal +'" name="pass[]" size="10">');
}
for( var j = 0; j<data['detail'].length; j++) {
var List = ["<tr><td>" + data['detail'][i].type + "</td><td>"+data['detail'][i].DB+"</td><td>"+data['detail'][i].LD+"</td><td>"+data['detail'][i].Prof+"</td><td>"+data['detail'][i].Server_stat+"</td></tr>"];
}
$("#bodywallet").append(List);
},
});
});
})
html code
<table class="table" id="wallet">
<thead class=" text-primary">
<tr>
<th class="text-left">Type</th>
<th class="text-left">Date_Bought</th>
<th class="text-left">Expires</th>
<th class="text-left">Profit</th>
<th class="text-left">Status</th>
</tr>
</thead>
<tbody class="text-left" id="bodywallet" >
</tbody>
</table>
this is what my data should be display on table
but it is displaying the first record only
i have checked json is bringing all the required data. what i have done wrong what is the mistake.any help will be appreciated. thanks
php code
while($row2 = mysqli_fetch_array($alEmailrslt))
{
$json_array['detail'][] = $row2;
}
echo json_encode($json_array);

You are putting everything in an array I and appending it every round.
You should use something like this instead:
success: function (data) {
var data = JSON.parse(data);
var list = []; // only one array
for (var j = 0; j < data['detail'].length; j++) {
// push to this array instead of overwriting the variable
list.push("<tr><td>" + data['detail'][j].type + "</td><td>" + data['detail'][j].DB + "</td><td>" + data['detail'][j].LD + "</td><td>" + data['detail'][j].Prof + "</td><td>" + data['detail'][j].Server_stat + "</td></tr>");
}
// update html once
// the join "glues" all parts of the array into one string
$("#bodywallet").append(list.join());
}

I think your list is not getting updated every time and the simplest approach would be, please find below code snippet:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>

Related

I want to make HTML table from array

The task is to fill the table with data from arrays id, name and price.
What am I doing wrong?
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
It doesn't work, because your input data is not organised as an array of objects, but as an object of arrays (which is less OOP).
As I prefer the array of objects as data structure, I would suggest to (temporarily) convert to that structure, and then your loop will work as expected:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(array, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
As an unrelated remark, I would suggest using jQuery more in the process of building the table. This will also avoid problems you might get when your data has < or & characters in it immediately followed by letters, as that would be interpreted as HTML:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
$('#tableContainer').empty().append($("<table>").addClass("mainTable").append(
$("<tr>").append(
$("<th>").text("id"),
$("<th>").text("name"),
$("<th>").text("price")
),
...array.map(value =>
$("<tr>").append(
$("<td>").text(value.id),
$("<td>").append($("<img>", { src: value.name })),
$("<td>").text(value.price)
)
)
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
Your data structure is not iterable. So you need to either change your data structure to be a list [{id: '1111', name: 'name1', price: 1111}], or you need to assume that all lists (id, name, price) are the same length, and use that length for the iteration.
As other answers detail how to use an iterable data structure, I'll handle the other method, where your data is already in this format, and won't change.
For this method, find the length of one property (id, name or price), and iterate through all of them using the index. Here is an example.
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
data.id.forEach((value, index) => {
table += ('<tr>');
table += ('<td>' + data.id[index] + '</td>');
table += ('<td><img src="' + data.name[index] + '"></td>');
table += ('<td>' + data.price[index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
You're processing the data as if it were structured as a single array, like this:
data = [
{
id: 1986,
name: "name1",
price: 1148
}
]
However, your data contains three arrays, not one:
data = {
id: [...],
name: [...],
price: [...],
}
If the data was structured like the first example, then value would contain an object for each array element, with the properties id, name and price available.
An option is to convert the first data structure to the second:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
Then, use the mappedData and access the properties as you're already doing, as follows:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(dataMapped, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data["id"], function(index, value){
table += ('<tr>');
table += ('<td>' + value + '</td>');
table += ('<td><img src="' + data["name"][index] + '"></td>');
table += ('<td>' + data["price"][index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
There ways to iterate the data as you defined it but I think it's better to define it in a proper way, as an array of entities ($.each is to iterate through an array):
[
{
"id": "1986",
"name": "name1",
"price": 1148
},
{
"id": "1990",
"name": "name2",
"price": 1396
},
];
Without changing the input you can do this.
var data = {
"id": ["1986", "1990", "1989", "1985", "1988", "1987"],
"name": ["name1", "name2 ", "name3 ", "name4", "латунь матовая ", "name5"],
"price": [1148, 1396, 2775, 1270, 1396, 1270]
};
document.getElementById("tableContainer").innerHTML = data.id
.map((id,i) => `<tr><td>${id}</td>
<td><img src="${data.name[i]}"></td>
<td>${data.price[i]}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
I also recommmend you change the input to an array of objects. It makes the parsing simpler
var data = [
{ "id": "1986", "name": "name1", "price": 1148},
{ "id":"1990", "name": "name2", "price": 1396},
{ "id":"1989", "name": "name3", "price": 2775},
{ "id":"1985", "name": "name4", "price": 1270},
{ "id":"1988", "name": "латунь матовая ", "price": 1396},
{ "id":"1987", "name": "name5", "price": 1270}
];
document.getElementById("tableContainer").innerHTML = data
.map(({id,name,price}) => `<tr><td>${id}</td>
<td><img src="${name}"></td>
<td>${price}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>

Search function to include space

I am trying to build a search function that would allow me to search Word 1 Word 2 ... Word 'n'.
The code below allows me to search through table rows. Results are presented when there is a 1:1 match (Ignoring case). I would like to search using combinations separated by spaces.
Table data sample as below.
AAA_BBB_CCC_DDD.pdf
EEE_FFF_GGG_HHH.pdf
HTML
<script>
$(function(){
$(function(){
var requestUri = "<<URL>>/_api/web/GetFolderByServerRelativeUrl('<<Folder>>')/Files?$filter=(substringof(%27.pdf%27,Name)%20or%20substringof(%27.PDF%27,Name))&$top=1000";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="Table" style="width:100%"><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + [i+1] + '</td>';
tableContent += '<td>' + objItems[i].Name + '</td>';
tableContent += '<td>' + "<a target='iframe_j' href='<<URL>>" + objItems[i].ServerRelativeUrl + "'>" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
$('#TDGrid').append(tableContent);
}
});
});
</script>
<div id="div">
<input class="form-control mb-2" id="TDSearch" type="text" placeholder=" Search">
<table id='Table' class="table table-striped table-sm small">
<tr>
<td>
<div id="TDGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
Current search function
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
You can convert string to array and then make a function, which will check match for strings of that array.
Something like
$(document).ready(function() {
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
var valueArr = value.split(' ');
$("#TDGrid tr").filter(function() {
$(this).toggle(checkIfValuePresent($(this).text().toLowerCase(), valueArr));
});
});
});
function checkIfValuePresent(currRowText, valuesarr) {
let isfound = false;
for (let i = 0; i < valuesarr.length; i++) {
if (currRowText.indexOf(valuesArr[i] > -1)) {
isfound = true;
break;
}
}
return isfound;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='TDSearch'>
split on space, join all strings with | between them for a combined regex string search, case insensitive.
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle(new RegExp(value.replace(/\./g,'[.]').split(' ').join('|'),'gi').test($(this).text()))
});
});
});

How to update values in json through user input in jquery?

I have 3 text boxes and when I enter the values and click add button it get added in new JSON and table and when I click particular field to edit it should update the linked json values with the new updated one.
I have two hidden fields:
$(document).ready(function() {
var departments = [{
"dep_id": 1,
"dep_name": "Account",
"deptnum": 10
},
{
"dep_id": 2,
"dep_name": "Software",
"deptnum": 20
},
{
"dep_id": 3,
"dep_name": "Hardware",
"deptnum": 30
},
{
"dep_id": 4,
"dep_name": "IT",
"deptnum": 40
}
];
var json = [];
$("#btn").click(function() {
if ($("#dept").val() && $("#name").val() && $("#eid").val()) {
var eid = $("#eid").val();
var name = $("#name").val();
var dept_id = $('#dept').val();
var counter = $('#counter').val();
counter++;
// var depart = departments.length;
for (var i in departments) {
var dep_obj = departments[i];
if (dep_obj.dep_id == dept_id) {
var dep = dep_obj;
}
}
var emp = {
"eid": eid,
"name": name,
"dept": dep,
};
var j_emp = JSON.stringify(emp);
console.log(j_emp);
json.push(j_emp);
var obj = JSON.parse(j_emp);
var x = '<tr><td id="eidA' + counter + '">' + obj.eid + '</td>' +
'<td id="nameA' + counter + '">' + obj.name + '</td>' +
'<td id="deptA' + counter + '">' + obj.dept.deptnum + '</td>' +
'<td id="deptnoA' + counter + '">' + obj.dept.dep_name + '</td>' +
'<td><input type="button" class="btn btn-primary" value="Edit" id="bEdit' + counter + '" data-id="' + obj.dept.dep_id + '" data-counter="' + counter + '"></td></tr>';
$(" #tab tr:last").after(x);
$("#counter").val(counter);
$("#eid").val('');
$("#name").val('');
$("#dept").val('');
$("#bEdit" + counter).unbind('click');
$("#bEdit" + counter).bind('click', form);
}
});
function form() {
var editCounter = $(this).data('counter');
var id = $(this).data('id');
var eId = $('#eidA' + editCounter).text();
var name = $('#nameA' + editCounter).text();
$('#eid').val(eId);
$('#name').val(name);
$('#dept').val(id);
$('#chosen_counter').val(editCounter);
$('#btn').hide();
$('#btn1').show();
$("#btn1").unbind('click');
$("#btn1").bind('click', update);
}
function update() {
var second = [];
var counter = $('#chosen_counter').val();
var eid = $('#eid').val();
var name = $('#name').val();
var dept_id = $('#dept').val();
for (var i in departments) {
var dep_obj = departments[i];
if (dep_obj.dep_id == dept_id) {
var dep = dep_obj;
}
}
var a = $('#eidA' + counter).text(eid);
var b = $('#nameA' + counter).text(name);
var c = $('#deptA' + counter).text(dep.deptnum);
var d = $('#deptnoA' + counter).text(dep.dep_name);
$('#bEdit' + counter).data('id', dep.dep_id);
$('#eid').val('');
$('#name').val('');
$('#dept').val(0);
$('#chosen_counter').val(0);
$("#btn1").unbind('click');
$("#btn").show();
$("#btn1").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="counter" value="0" />
<input type="hidden" id="chosen_counter" value="0" />
<input type="text" class="input" id="eid" />
<input type="text" class="input" id="name" />
<select class="input" id="dept">
<option value="0">Select department</option>
<option value="1">10</option>
<option value="2">20</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
<input type="button" class="btn btn-success" value="Save" id="btn">
<input type="button" class="btn btn-success" value="Update" id="btn1">
<div class="show">
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Dept_No</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I tried this:
But I think I am doing it wrong...I am new to this so its hard for me to understand.. I am able to fetch these values in new json but I don't know to update the values in old one.
emp.foreach(function check(value, index, array) {
if (value.choosencounter == counter) {
emp[index].eid = eid;
emp[index].name = name;
emp[index].deptA = dep_val;
emp[index].deptnoA = dep_name;
}
});
Here you go, I think you could easy understand the code.
var j_emp = [];
var currentEditID = 0;
var departments = [{
"dep_id": 1,
"dep_name": "Account",
"deptnum": 10
},
{
"dep_id": 2,
"dep_name": "Software",
"deptnum": 20
},
{
"dep_id": 3,
"dep_name": "Hardware",
"deptnum": 30
},
{
"dep_id": 4,
"dep_name": "IT",
"deptnum": 40
}
];
$(document).ready(function() {
$("#btn").click(function() {
if ($("#dept").val() && $("#name").val() && $("#eid").val()) {
var emp = fetchFieldValues();
j_emp.push(emp);
renderTable();
clearFieldValues();
}
});
});
function edit(item) {
let id = $(item).attr('id');
currentEditID = id;
let emp = j_emp.filter(e => {
return e.id == id;
})[0];
$('#eid').val(emp.eid);
$('#name').val(emp.name);
$('#dept').val(emp.dept.dep_id);
$('#btn').hide();
$('#btn1').show();
}
function update(prevVal) {
var emp = fetchFieldValues();
for (var i = 0; i < j_emp.length; i++) {
if (j_emp[i].id == currentEditID) {
j_emp[i] = emp;
j_emp[i].id = currentEditID;
}
}
renderTable();
clearFieldValues();
$("#btn").show();
$("#btn1").hide();
}
function renderTable() {
$("#tab tbody").empty();
let html = '';
j_emp.forEach(obj => {
html += '<tr><td>' + obj.eid + '</td>' +
'<td>' + obj.name + '</td>' +
'<td>' + obj.dept.deptnum + '</td>' +
'<td>' + obj.dept.dep_name + '</td>' +
'<td><input type="button" class="btn btn-primary edit-button" id="' + obj.id + '" value="Edit" onclick="edit(this)"></td></tr>';
});
$("#tab tbody").append(html);
}
function fetchFieldValues() {
return {
"eid": $("#eid").val(),
"name": $("#name").val(),
"dept": departments.filter(e => {
return e.dep_id == $('#dept').val();
})[0],
'id': new Date().getTime()
};
}
function clearFieldValues() {
$("#eid").val('');
$("#name").val('');
$("#dept").val('');
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<input type="hidden" id="counter" value="0" />
<input type="hidden" id="chosen_counter" value="0" />
<input type="text" class="input" id="eid" />
<input type="text" class="input" id="name" />
<select class="input" id="dept">
<option value="0">Select department</option>
<option value="1">10</option>
<option value="2">20</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
<input type="button" class="btn btn-success" value="Save" id="btn">
<input type="button" class="btn btn-success" value="Update" id="btn1" onclick="update()">
<div class="show">
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Dept_No</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Make entire table editable and saving the changes on click

I'm trying to make an editable table such that when the user clicks on the 'edit' button, every table data cell get placed inside an input form that the user can type in and change the information. Once the user is done, they may click the edit button again so that all of the input fields go away and the changes made are saved and displayed on the table.
I have made it so that every single data in every table data cell gets placed inside an input field when the user clicks the single 'edit' button. However, I'm having a really rough time trying to figure out how to remove the input boxes and display all the updated table cells. I was thinking of placing "contenteditable" withing every td and changing it to true/false would work, but I couldn't figure it out.
I'm using local storage for this, but I just need help on this one thing. Any help would be greatly appreciated.
var retrieveContacts = localStorage.getItem("contacts");
var newVariable = JSON.parse(retrieveContacts);
var isEdit = 0; // is the table in edit mode? 0- false 1- true
// set to 0 (false) by default
$.each(newVariable, function(){
$('#tableStyles').append('<tr>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].email + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].firstname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].lastname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].prefix + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].title + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].company + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].phone + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].fax + '</td>' +
'</tr>');
i++;
});
$('#createCont').click(function(){
var newRow = "<tr style='height: 35px;'><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
$('#tableStyles').append(newRow);
newVariable.push({"email": "",
"firstname": "",
"lastname": "",
"prefix": "",
"title": "",
"company": "",
"phone": "",
"fax": ""});
localStorage.setItem("contacts", JSON.stringify(newVariable));
});
$('#editCont').click(function(){
if(isEdit == 0){
var j = 0;
var trCount = 2; // up to newVariable.length+1
var tdCount = 1; // up to 8
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
var testing2 = testing1.html("<input type='text' value='" + testing1.html() + "'/>");
}
tdCount = 1;
}
trCount = 2;
tdCount = 1;
isEdit = 1;
//console.log("isEdit set to 1");
} else if(isEdit == 1) { // if the edit button is clicked and we are already editing the form,
// then we have take out the input boxes and save all changes.
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
}
tdCount = 1;
}
isEdit = 0;
//console.log("isEdit set to " + isEdit);
}
});
I would like to offer you a better solution. You can place the input field directly into the table cells and use the readonly attribute to set it editable.
Here is the code:
document.getElementById("edit").addEventListener("click", function() {
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = false;
}
document.getElementById("save").style.display = "inline-block";
});
document.getElementById("save").addEventListener("click", function() {
var data = {};
data.name = document.getElementById("name").value;
data.email = document.getElementById("email").value;
// window.localStorage.formData = JSON.stringify(data);
// localStorage will not work in this snippet editor
// uncomment it in your code
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = true;
}
document.getElementById("save").style.display = "none";
});
table input[type="text"] {
/* place any styling here */
}
table input[type="text"]:read-only {
border: none;
}
#save {
display: none;
}
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name" value="Some Name" readonly /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" value="Email address" readonly /></td>
</tr>
</table>
<input type="button" id="edit" value="Edit" />
<input type="button" id="save" value="Save" />
</form>
Please, tell me if it works for you!

Add items of array in javascript

I want to add price of all items in form of total from below code.
document.getElementById('form-signin').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
console.log(bill);
}
e.preventDefault();
}
function fetchResult(){
var bill = JSON.parse(localStorage.getItem('bill'));
var result = document.getElementById('total');
result.innerHTML='';
for(var i=0;i < bill.length;i++){
var items= bill[i].items;
var date= bill[i].date;
var price= bill[i].price;
result.innerHTML+= '<table class="table table-bordered">' + '<tr>'+
'<th>'+'Items'+'</th>'+
'<th>'+'Date'+'</th>'+
'<th>'+'Price'+'</th>'+
'</tr>'+ '<tr>'+
'<td>'+ items + '</td>'+
'<td>'+ date+ '</td>'+
'<td>'+ price + '</td>'+
'</tr>'+ '</table>';
}
This is output of aboce. Now how to calculate total ??
Eduardo's sample will work, but I went a little further if you're interested in another way to accomplish what you're doing. I made some changes to help you prevent duplicating column headers and clean up the table generation a bit. This code does require jQuery however, and the table needs to already exist.
The form is just there because I needed something to test against... you can remove that part.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form>
Items: <input type="text" id="items"><br>
Date: <input type="text" id="date"><br>
Price: <input type="text" id="price"><br>
<input type="submit" value="Submit" onClick="saveItem()" >
</form>
<table id="tbl-items" class="table table-bordered"><thead><tr><th>Items</th><th>Date</th><th>Price</th></tr></thead><tbody id="tbl-items-body"></tbody></table>
<script>
document.getElementById('form-signin').addEventListener('submit', saveItem);
function saveItem(){
var bill=[];
var expense= { // didn't need the variables.
items: document.getElementById('items').value,
date: document.getElementById('date').value,
price: document.getElementById('price').value
}
if(localStorage.getItem('bill') != null){
bill = JSON.parse(localStorage.getItem('bill'));
}
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill))
console.log(bill);
}
function fetchResult(){
var bill = JSON.parse(localStorage.getItem('bill'));
var totalItems = 0;
var totalPrice = 0;
for(var i=0;i < bill.length;i++){
totalItems++;
totalPrice += bill[i].price;
$("#tbl-items-body").append(
$('<tr>').append(
'<td>' + bill[i].items + '</td><td>' + bill[i].date + '</td><td>' + bill[i].price + '</td>'
)
);
}
$("#tbl-items-body").append(
$('<tr>').append(
'<td>Total Items: ' + totalItems + '</td><td>Total Price: ' + totalPrice + '</td>'
)
);
}
</script>
In your fetchResult function while you are adding the price values and displaying in table, add to price to a total variable, then display.
function fetchResult(){
...
result.innerHTML='';
var total = 0;
for(var i=0;i < bill.length;i++){
var items= bill[i].items;
var date= bill[i].date;
var price= bill[i].price;
total += price;
result.innerHTML+= '<table class="table table-bordered">' + '<tr>'+
'<th>'+'Items'+'</th>'+
....
<span> total </span>
}

Categories

Resources