I was using SQLite in html5 and it worked fine. But the thing was the rows which I was displaying in the page itself were not looking that good. I used innerhtml for displaying the rows as inserted by the user.
Here is the script
function showRecords() {
results.innerHTML = '';
// This function needs a single argument, which is a function that takes
// care of actually executing the query
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
dataset = result.rows;
for ( var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
results.innerHTML += '<li>' + item['lastName'] + ' , '
+ item['firstName']
+ ' <a href="#" onclick="loadRecord(' + i
+ ')">edit</a> '
+ '<a href="#" onclick="deleteRecord(' + item['id']
+ ')">delete</a></li>';
}
});
});
}
/**
* Loads the record back to the form for updation
*
* #param i
*/
function loadRecord(i) {
var item = dataset.item(i);
firstName.value = item['firstName'];
lastName.value = item['lastName'];
phone.value = item['phone'];
id.value = item['id'];
}
/**
* Delete a particular row from the database table with the specified Id
*
* #param id
*/
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql(deleteStatement, [ id ], showRecords, onError);
});
resetForm();
}
So in the code showRecords() method, I have hard coded the data to be displayed. What I want is, that data should be displayed in proper tabular format. I know I have to create elements in JavaScript for dynamic table generation but I am unable to do so and also to display the contents inside table.
Everytime user fills up the form and clicks insert button, insert statement gets executed and then showRecords() method is invoked. I am not able to figure out the proper soluton.
For a pure JavaScript solution, I think this (untested) will work:
function loadRecord(i) {
var item = dataset.item(i);
firstName.value = item.firstName;
lastName.value = item.lastName;
phone.value = item.phone;
id.value = item.id;
}
function showRecords() {
results.innerHTML = '';
// This function needs a single argument, which is a function that takes
// care of actually executing the query
db.transaction(function (tx) {
var i = 0,
table = document.createElement('table'),
tbody = document.createElement('tbody');
tx.executeSql(selectAllStatement, [], function (tx, result) {
var tr = {},
tdName = {},
tdEdit = {},
tdDel = {},
span = {},
aEdit = {},
aDel = {};
dataset = result.rows;
for (i = 0, item = null; i < dataset.length; i += 1) {
//create new table elements
tr = document.createElement('tr');
tdName = document.createElement('td');
tdEdit = document.createElement('td');
tdDel = document.createElement('td');
aEdit = document.createElement('a');
aDel = document.createElement('a');
//grab dataset row
item = dataset.item(i);
//set the name
tdName.innerText = item.lastName + ' , ' + item.firstName;
//create the edit link
aEdit.href = '#';
aEdit.onclick = loadRecord(i);
aEdit.innerText = ' edit ';
tdEdit.appendChild(aEdit);
//create the delete link
aDel.href = '#';
aDel.onclick = deleteRecord(item.id);
aDel.innerText = ' delete ';
tdDel.appendChild(aDel);
//append to row
tr.appendChild(tdName);
tr.appendChild(tdEdit);
tr.appendChild(tdDel);
//append to body
tbody.appendChild(tr);
}
});
table.appendChild(tbody);
results.innerHTML = table.outerHTML;
});
}
/**
* Delete a particular row from the database table with the specified Id
*
* #param id
*/
function deleteRecord(id) {
db.transaction(function (tx) {
tx.executeSql(deleteStatement, [id], showRecords, onError);
});
resetForm();
}
Related
I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you
I've a function in javascript which creates table of properties dynamically:
// update table
PropertyWindow.prototype._update = function (text) {
if (text === void 0) { text = "<no properties to display>"; }
this._propertyWindow.html(text);
};
PropertyWindow.prototype._onModelStructureReady = function () {
this._assemblyTreeReadyOccurred = true;
this._update();
};
// create row for property table
PropertyWindow.prototype._createRow = function (key, property, classStr) {
if (classStr === void 0) { classStr = ""; }
var tableRow = document.createElement("tr");
tableRow.id = "propertyTableRow_" + key + "_" + property;
if (classStr.length > 0) {
tableRow.classList.add(classStr);
}
var keyDiv = document.createElement("td");
keyDiv.id = "propertyDiv_" + key;
keyDiv.innerHTML = key;
var propertyDiv = document.createElement("td");
propertyDiv.id = "propertyDiv_" + property;
propertyDiv.innerHTML = property;
tableRow.appendChild(keyDiv);
tableRow.appendChild(propertyDiv);
return tableRow;
};
I want to take that generated table into json/xml and save this into a new file, how would I do this?
You can basically loop through the generated table like below and convert it into json with the following code
var myRows = [];
var $headers = $("th");
//your table path here inside the selector
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($headers[cellIndex]).html()] = $(this).html();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));
Possible duplicate
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
The function above gets an input value from a field in a set of rows using jQuery .val()
var table = document.getElementById('DYN_6000-LISTSAPLMEGUI-tab');
var t = table.rows.length;
//getting current blank cell ID and upping the blank cell ID to the new last cell
var new_cell_id = table.rows.item(t-1).id;
var old_cell_id = "DYN_6000-LISTSAPLMEGUI-key-" + t;
table.rows.item(t - 1).id = old_cell_id;
table.rows.item(t - 1).onmouseover = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onmouseout = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onclick = function () { showItemDetailDropDown_click(old_cell_id); };
//create new row and table
var drop_down_height = document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height;
document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height = (parseInt(drop_down_height.replace("px", "")) + 18) + "px";
var new_row = table.insertRow(t-1);
var new_cell = new_row.insertCell(0);
new_row.insertCell(1);
//set new row and cell properties
new_row.id = new_cell_id;
new_row.classList.add('urNoUserSelect');
new_row.style.width = "100%";
new_row.style.height = "18px";
new_row.onmouseover = function () { showItemDetailDropDown_hover(new_cell_id); };
new_row.onmouseout = function () {showItemDetailDropDown_hover(new_cell_id); };
new_row.onclick = function () {showItemDetailDropDown_click(new_cell_id);};
new_cell.classList.add('urIlb2I');
new_cell.classList.add('urColorTxtStandard');
var new_item = t;
new_cell.innerHTML = "[ " + new_item + " ]";
var zyx = "grid#21.125#" + row + ",2#if";
document.getElementById(zyx).value = new_item;
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = new_cell.innerHTML;
checkButton('keyboard');
This JS function is part of an if else statement that checks if there is a new value in each row and adds a sequential number to a dropdown item menu below the table. My question is: How do I append or concatenate the first value (description) into the dropdown menu after the number? For example,
[ 1 ] descriptionInput (the value)
Everything works I just don't know how to pass the jQuery function back to JS or append each value.
i'm trying to retrieve the data from the database for web application using webSQL ,but i'm unable to get the data from database. I'm very new to this. I tried like this
var DB_NAME = "database";
var DB_VERSION = "";
var DB_TITLE = "";
var DB_BYTES = 50 * 1024 * 1024;
var db = openDatabase(DB_NAME, DB_VERSION, DB_TITLE, DB_BYTES);
//Retrieve Rows from Table
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM Data;",
[],
function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
});
Thanks in Advance.
This is how i have done.. and this is working for me.
// global variables
var db;
var shortName = 'Books';
var version = '1.0';
var displayName = 'BooksDB';
var maxSize = 200000;//65535;
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
// this line tries to open the database base locally on the device if it does not exist, it will create it and return a database object stored in variable db
db = openDatabase(shortName, version, displayName,maxSize);
// this line clears out any content in the #lbUsers element on the page so that the next few lines will show updated content and not just keep repeating lines
$('#lbUsers').html('');
// this next section will select all the content from the User table and then go through it row by row appending the UserId FirstName LastName to the #lbUsers element on the page
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM books;', [], function(transaction, result) { if (result != null && result.rows != null) { for (var i = 0; i < result.rows.length; i++) { var row = result.rows.item(i); $('#lbUsers').append('<br>' + row.book_title + '. ' + row.book_isbn+ ' ' + row.book_price); } } },errorHandler); },errorHandler,nullHandler);
return;
alert('in list end');
}
// this is called when a successful transaction happens
function successCallBack() {
alert("DEBUGGING: success");
}
function nullHandler(){
alert('null handler');
};
Here is my function:
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET product = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
Here is the call:
<span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['product'] + '</span>
I would like to add a parameter to the call so that I can use the function for multiple columns. Here is what I'm trying but it doesn't work:
<span contenteditable="true" onkeyup="updateRecord('+item['id']+', "product", this)">'+
item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET " + column + " = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
They should do the exact same thing, I only specified the product column in the call instead of in the function. Is my syntax incorrect, am I missing something?
Edit:
Here is the full function in which the call is located:
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM products", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', "product", this)">'+
item['product'] + '</span> x</li>';
}
});
});
}
Update: Ok, then the issue only lies in using double quotes for product. Use single quotes and escape them:
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', \'product\', this)">' + ...;
But you really should consider to refactor your code. E.g. you could write it like this:
var results = document.getElementById('results');
var container = document.createDocumentFragment();
for (var i = 0, l = result.rows.length; i < l; i++) {
var item = result.rows.item(i);
var li = document.createElement('li');
var span = document.createElement('span');
span.setAttribute('contenteditable', 'true');
span.onkeyup = (function(item) {
return function() {
updateRecord(item['id'], 'product', this);
}
}(item));
span.innerHTML = item['product'];
var a = document.createElement('a');
a.href = '#';
a.onclick = (function(item) {
return function() {
deleteRecord(item['id'])
}
}(item));
a.innerHTML = 'x';
li.appendChild(span);
li.appendChild(a);
container.appendChild(li);
}
results.appendChild(container);
It is more code but easier to maintain in the long run...
You have syntax and quotation issues. This should work:
onkeyup="updateRecord('item[\'id\']', 'product', this)"
But the code seems a bit weird to me. Is this in your actual HTML or are you echoing or printing it? Because
<span...>'+ item['product'] + '</span>
looks weird in HTML. It will literally put '+ item['product'] + ' inside the <span> tag. Please post a more complete version of your code.