Mistake with an insert into Web SQL from text input - javascript

so I'm still learning JavaScript and am having an issue with something I am working on. When trying to enter something into two separate text inputs it will only default to the gotError function, nothing is being inserted into the Web SQL and then read back to the list.
The JavaScript:
function openDb() {
db = openDatabase('DName', '1', 'NameV', 2 * 1024 * 1024);
//(Database Name, Version, Display Name, Size )
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS Logs (id unique, person TEXT, place TEXT)");
});
}
document.addEventListener('init', function(event) {
if(event.target.id == 'mylist') {
openDb();
storeItems();
}
});
function gotError() {
alert('Something went wrong.');
}
function gotSuccess() {
storeItems()
}
function storeItems()
{
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Logs", [], listItems, gotError);
});
}
function listItems(rs)
{
var output = '';
var list = document.getElementById('tList');
for(i = 0; i < rs.rows.length; i++)
{
stuff = person && place;
var row = rs.rows.stuff(i);
output += "ons-list-item>" + row.stuff +
"<div class=\"right\"> <ons-button><ons-icon icon=\"trash\"></ons-icon></ons-button></div>" +
"</ons-list-item>";
}
list.innerHTML = output;
}
function addItem()
{
var textbox = document.getElementById("person", "place");
var value = textbox.value;
db.transaction(function(tx)
{
tx.executeSql("INSERT INTO Logs (person,place) VALUES (?,?)", [value], gotSuccess, gotError)
});
textbox.value = "";
fn.load("mylist.html");
}
The HTML:
<template id="mylist.html">
<ons-page id='mylist'>
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="fn.open()">
<ons-icon icon="md-menu"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center">
My List
</div>
</ons-toolbar>
<div>
<ons-input type="text" class="select-input--underbar" id="person" placeholder="Enter person here . . ."></ons-input>
<ons-input type="text" class="select-input--underbar" id="place" placeholder="Enter place here . . ."></ons-input>
<ons-button modifier="large" onclick="addItem()">Add Item</ons-button>
</div>
<ons-list id='tList'>
<ons-list-header>Listed Items:</ons-list-header>
<ons-list-item>
</ons-list-item>
</ons-list>
</ons-page>
</template>
</ons-page>
</template>
Originally the code was supposed to insert have two text inputs that would need to be filled out, a button would be pressed to add them to the list, then display the db contents for person and place. Then each time the page was opened or closed it would re-read the contents of the db and redisplay them on the list.

This is an error:
stuff = person && place;
Because:
You are declaring stuff as a global variable (error in strict mode).
person and place are undeclared
Probably this error is being catch'ed and then gotError is executed. Probably you would have seen that if declared the function with an argument:
function gotError(error) {
console.error('Something went wrong:', error);
}

Related

How do I get cell values on click event from webpage tabs after the first one?

I have tried javascript and JQuery. I know how to write the code to get the cell values from my first tab but the same function does not work on the other tabs on my webpage. It seems as if the table in my other tabs is just a view. I am new to javascript and JQuery so think I might be missing something easy. I have used ".on" in my click function and that doesn't help. Here is the Javascript code and JQuery code, both work by grabbing the cell value I click but only for the first tab:
JavaScript
init();
function init(){
addRowHandlers('customerTable');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var cid = '';
var name = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
cid = table.rows[this.i].cells[0].innerHTML;
name = table.rows[this.i].cells[1].innerHTML;
alert('cid: '+cid+' name: '+name);
};
}
}
}
JQuery
$('#customerTable').find('tr').click(function() {
var $id = $(this).closest("tr")
.find(".custId")
.text();
var $name = $(this).closest("tr")
.find(".custName")
.text();
alert($name);
$('.defaultTextBox.text_custId:text').val($id);
$('.defaultTextBox.text_custName:text').val($name);
});
In the end my goal is to get the elements clicked and set the text in my text boxes to those values, which you can see I did in the JQuery, but it only works on my first page. I need the click in my table to work on all tabs. Thanks in advance!
Edit
<div id="removeCustomer" class="tabcontent">
<h3>Pick a customer to remove!</h3>
<div class="container">
<br />
<h2 align="center">Search here to find the customer you want to remove</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by name, phone number, email, or state" class="form-control" />
</div>
</div>
<br />
<div class="result"></div>
</div>
</div>
The "removeCustomer" id is one of the tabs. So I have multiple tabs using the same, "result", which I think is the problem I just do not know how to solve it. If I Left out "result" it would not generate a table.
Here is the JQuery which uses a php file to connect to my database and get my data. And this is what generates result.
JQuery
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetchCustomers.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('div.result').html(data);
}
});
}
$('input.form-control').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
Thanks again.

Reinvestigating "Trying to make different HTML paragraph show depending on selection"

I asked about this previously but failed to provide enough detail so I thought I'd give credit where it's due (the responses were excellent, but didn't answer my issue because I'd failed to provide enough information) and start over.
So I have this pair of modals; one that accepts a text input, and one that gets input out of a dropdown selection, in google sheets and scripts (see hyperlinks) that is supposed to provide a different descriptive paragraph depending on which which selection the user has made from a dropdown step. Currently it just shows a single paragraph that doesn't change depending on selection. I want it to:
show id='PUBLIC' paragraph when Public is selected, show id='INTERNAL' when internal is selected. Etc. Etc.
Save their selection and send it to be pasted it where it's needed.
function AddValuesFromModal(selectValue) {
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log("Getting document log...");
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
console.log("Got document!");
console.log("Selected value: " + selectValue);
console.log("Start setting value....");
infoSheet.getRange('C4').setValue(selectValue);
console.log("Value has been set!");
}
function myFunk() {
// Display a dialog box for each field you need information for.
var documentProperties = PropertiesService.getDocumentProperties();
var ui = SpreadsheetApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter owners person's name', ui.ButtonSet.OK);
var nameResponse = ui.prompt("Enter the name of the document OWNER");
var salesperson = nameResponse.getResponseText();
var documentProperties = PropertiesService.getDocumentProperties();
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
var date = new Date();
var htmlDlg = HtmlService.createHtmlOutputFromFile("HTML_myHtml")
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
var modal = SpreadsheetApp.getUi();
modal.showModalDialog(htmlDlg, "Document Classification");
//Get Current Document ID
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log(documentId);
//Get the document body as a variable
var body = SpreadsheetApp.openById(documentId).getDataRange().getValues();
console.log(body);
//Insert the entries into the document
infoSheet.getRange('C5').setValue(salesperson);
infoSheet.getRange('C8').setValue(date);
}
<form id="docType">
<select id="selectDocumentType" name="documentClass" onchange='CheckSelect(this.value);'>
<option value="PUBLIC">Public</option>
<option value="INTERNAL">Internal</option>
<option value="CONFIDENTIAL">Confidential</option>
<option value="SECRET">Secret</option>
</select>
<body>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:block;" class="light work"
id="Choose" >Please Choose any one</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="PUBLIC" >Wizard Is working</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="INTERNAL" >Wizard Is Twerking</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="CONFIDENTIAL" >Wizard Is Laughing</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="SECRET" >Wizard Is Eating</p>
</body>
<hr/>
<input type="button" onClick="formSubmit();" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function HideAll(val)
{
var all = document.getElementsByClassName(val);
for(var i =0; i<all.length; i++)
all[i].style.display = 'none';
}
function CheckSelect(val){
HideAll('work');
document.getElementById(val).style.display='block';
}
function formSubmit(){
Submit();
}
function Submit() {
var selectedValue = $('#selectDocumentType').val();
console.log(selectedValue);
google.script.run
.withSuccessHandler(closeIt)
.AddValuesFromModal(selectedValue);
};
function closeIt(){
google.script.host.close();
};
</script>
I updated the script. "CheckColors" should have been "CheckSelect". Bad version control facepalm.

Store toggle input to SQLite database using Javascript

now i'm working with Intel XDK using Ionic framework.
i've succesfully store data to database using SQLite database, and now i want to store Toggle input button to database but i don't know how to do that.
Here is my code to input to SQLite :
var insertKasir = "INSERT INTO Kasir (namamenu) VALUES (?)";
var selectKasir = "SELECT * FROM Kasir";
function insertRecord(){
var namamenutemp = $('input:text[id=namamenu]').val();
db.transaction(function (tx) { tx.executeSql(insertKasir, [namamenutemp]); });
}
function showRecords() {
$("#results").html('')
db.transaction(function (tx) {
tx.executeSql(selectKasir, [], function (tx, result) {
dataset = result.rows;
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
var linkeditdelete = '' + item['namamenu'] + '';
$("#results").append(linkeditdelete);
}
});
});
}
and now i want to add some toggle button and store it to database, some thing like this:
<li class="item item-toggle widget uib_w_377 pengaturan-margin" data-uib="ionic/toggle" data-ver="0">Pembelian
<label class="toggle">
<input type="checkbox">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
how can i store the toggle to my sqlite database ?

Web sql database implementation error

I have the following well running jsFiddle which shows proper implementation of web sql feature:
https://jsfiddle.net/Trae/76srLbwr/
If I copy the very same file on my .html page and try to run. It is not running.
HTML:
<html>
<head></head>
<body>
<h1>WebSQL Example</h1>
<div id="controls">
<p>Add a car to the database</p>
<label>Make:</label>
<input type="text" id="carmake" />
<br />
<label>Model:</label>
<input type="text" id="carmodel" />
<br />
<button type="button" id="addcar" onclick="addCar();">Add Car</button>
</div>
<div id="carlistholder">
<h3>Your Cars</h3>
<ul id="carlist"></ul>
</div>
<p><strong>Note: </strong>You can leave this page and when you return the cars you entered will still be here!</p>
<script>
//Test for browser compatibility
if (window.openDatabase) {
//Create the database the parameters are 1. the database name 2.version number 3. a description 4. the size of the database (in bytes) 1024 x 1024 = 1MB
var mydb = openDatabase("cars_db", "0.1", "A Database of Cars I Like", 1024 * 1024);
//create the cars table using SQL for the database using a transaction
mydb.transaction(function (t) {
t.executeSql("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY ASC, make TEXT, model TEXT)");
});
} else {
alert("WebSQL is not supported by your browser!");
}
//function to output the list of cars in the database
function updateCarList(transaction, results) {
//initialise the listitems variable
var listitems = "";
//get the car list holder ul
var listholder = document.getElementById("carlist");
//clear cars list ul
listholder.innerHTML = "";
var i;
//Iterate through the results
for (i = 0; i < results.rows.length; i++) {
//Get the current row
var row = results.rows.item(i);
listholder.innerHTML += "<li>" + row.make + " - " + row.model + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)";
}
}
//function to get the list of cars from the database
function outputCars() {
//check to ensure the mydb object has been created
if (mydb) {
//Get all the cars from the database with a select statement, set outputCarList as the callback function for the executeSql command
mydb.transaction(function (t) {
t.executeSql("SELECT * FROM cars", [], updateCarList);
});
} else {
alert("db not found, your browser does not support web sql!");
}
}
//function to add the car to the database
function addCar() {
//check to ensure the mydb object has been created
if (mydb) {
//get the values of the make and model text inputs
var make = document.getElementById("carmake").value;
var model = document.getElementById("carmodel").value;
//Test to ensure that the user has entered both a make and model
if (make !== "" && model !== "") {
//Insert the user entered details into the cars table, note the use of the ? placeholder, these will replaced by the data passed in as an array as the second parameter
mydb.transaction(function (t) {
t.executeSql("INSERT INTO cars (make, model) VALUES (?, ?)", [make, model]);
outputCars();
});
} else {
alert("You must enter a make and model!");
}
} else {
alert("db not found, your browser does not support web sql!");
}
}
//function to remove a car from the database, passed the row id as it's only parameter
function deleteCar(id) {
//check to ensure the mydb object has been created
if (mydb) {
//Get all the cars from the database with a select statement, set outputCarList as the callback function for the executeSql command
mydb.transaction(function (t) {
t.executeSql("DELETE FROM cars WHERE id=?", [id], outputCars);
});
} else {
alert("db not found, your browser does not support web sql!");
}
}
outputCars();
</script>
<style>
body {
font-family: sans-serif;
padding: 10px;
}
h1 {
font-weight: bold;
}
label {
font-size: small;
}
#controls {
padding-bottom: 5px;
border-bottom: 1px solid #000;
}
</style>
</body>
</html>
ERROR:
Can someone help me out when I am copying the same files, and opening in same browser Chrome (Version 51.0.2704.84), why is it not running from an html file?
I have a same problem when browse the html file directly in chrome. I can solve it creating a website in the IIS.
I hope to help you.
Daniel.-

innerHTML output with Javascript template

For my project I have to scan BLE-tags and show their RSSI for proximity.
The output of the BLEs is working with a JavaScript template.
<body>
<div id="header" data-role="header" data-theme="b">
<h1>BLE overview</h1>
</div>
</br>
<div data-role="content" id="home">
Initialize
Start Scan
Stop Scan
</div>
<ul data-role="list-view" class="devices"></ul>
<div data-role="content id="result">
<script type="text/template" id="device"> //start of the schript tag and output of the scanned BLEs
<ul data-role="listview">
<li data-address="{0}">
<h2>{1}</h2>
Connect
<div id="rssiop"> RSSI: <div> // value of the RSSI
</br>
</li>
</ul>
</script>
</div>
The function, which return the value of the rssi is following
function startScanSuccess(obj)
{
console.log("The RSSI value is:" + obj.rssi); // here I see the RSSI value on the console
if (obj.status == "scanResult")
{
console.log("Scan Result");
addDevice(obj.address, obj.name);
}
else if (obj.status == "scanStarted")
{
console.log("Scan Started");
}
else
{
console.log("Unexpected Start Scan Status");
}
}
and this is the function which gives the name and address of the scanned BLE out
function addDevice(address, name)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
console.log("Mein RSSI: " + obj.rssi);
document.getElementById("rssiop").innerHTML = "The RSSI value is:";
var template = $("#device").text().format(address, name);
$devices.append(template);
}
So everything is working and when I put the div-tag above the template script I can see the RSSI. Can anyone figure out why the innerHTML is in the template part not working?
I figured it out:
The Problem was that the innerHTML wasn't working, because I used the append()-command for the list output. I just had to add the rssi parameter to the addDevices function and it worked.
The correct code of the addDevice function:
function addDevice(address, name, rssi)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
var template = $("#device").text().format(address, name, rssi);
$devices.append(template);
}

Categories

Resources