Store toggle input to SQLite database using Javascript - 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 ?

Related

Mistake with an insert into Web SQL from text input

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);
}

Javascript (firebase): how can the firebase database key of a clicked item be obtained?

I have a firebase database structure like this
and I have a loop function
var jobTitle = document.getElementById('jobTitle');
var jobDescription= document.getElementById('jobDescription');
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var ref = database.ref('/Jobs/');
ref.on('value', gotData, errData);
}
})
var jobSnap = {};
function gotData(data) {
var date = Today;
var jobs = data.val();
var keys = Object.keys(jobs);
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
for (var i = 0; i<keys.length; i++) {
var k = keys[i];
var newCard = `
<li class="pos-card" id="pos_1">
<div class="content">
<div class="title new">`+jobs[k].JobTitle+`</div>
<div class="dept">Customer Service</div>
<div class="date">date</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>`+jobs[k].JobSummary+`</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
This is the function that submits the application to the DB under the respective job id.
function newApplication() {
var database = firebase.database();
var applicant_Name = document.getElementById('name').value;
var applicant_Number = document.getElementById('phone').value;
var applicant_email = document.getElementById('email').value;
var AuthorId = firebase.auth().currentUser.uid;
var cover_letter = document.getElementById('cover_letter').value;
var JobId = jobSnap.key;
var postData = {
ApplicantName: applicant_Name,
ApplicantNumber: applicant_Number,
Applicantemail: applicant_email,
Author: AuthorId,
Cover_letter: cover_letter,
};
var newPostKey = firebase.database().ref().child('Applications').push().key;
var updates = {};
updates['/Applications/' + newPostKey] = postData;
updates[ JobId + '/Applications/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
that retrieves all entries in the database Jobs node and display them like this
When a user clicks the apply button on a job an application fades in; all the code that retrieves the Jobs and application are in the same html file. What I need to do is find a way to capture the firebase job key of the job that was clicked so that i can save the job application under the respective jobs. I have tried many methods but still no luck how can I implement this?
You'll need to keep track of the key of each item in the HTML. A common way to do that is by injecting it into the id attribute in the HTML:
var newCard = `
<li class="pos-card" id="${k}">
Then you can use the id when the user clicks on an element to find the item in the database.
A more idiomatic way to write your code would be:
function gotData(data) {
var date = Today;
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
data.forEach(function(jobSnap) { // loop over all jobs
var key = jobSnap.key;
var job = jobSnap.val();
var newCard = `
<li class="pos-card" id="${key}">
<div class="content">
<div class="title new">${job.JobTitle}</div>
<div class="dept">Customer Service</div>
<div class="date">${date}</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>${job.JobSummary}</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
If the list is dynammic then you can assign it a unique id and add onclick listener
In your JS function,
Function name(value)
{
}

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.-

Odd behaviour of dropdown in Angular JS

I am making hybrid app using Angular JS, wherein there is an page which has two dropdown (select controls).
The thing should be,When I select the first dropdown the second one automatically should fill based on the data fetched on change of first doropdown; but what happens is on change of first dropdown the data is fetched but it is not getting bind to second dropdown immediately though the model of second dropdown gets the data fetched on selection of first dropdown, instead what happens is when i again change the first dropdown selection, the previous data gets bind to the second dropdown.
Below is my code for the same -
Car Make dropdown -
<select name="make"
ng-options="item.MakeId as item.Make for item in memberdetailData.VehicleData"
ng-model="memberdetailData.selected_Make_ID"
ng-change="vehiclemakeselected()">
Car Model Dropdown -
<select name="model" ng-disabled="memberdetailData.selected_Make_ID === {}"
ng-options="item.ModelId as item.Model for item in memberdetailData.Vehicle_Model"
ng-model="memberdetailData.selected_Model"></select>
Controller code -
$scope.vehiclemakeselected = function () {
console.log($scope.memberdetailData.selected_Make_ID);
//console.log($scope.memberdetailData.selected_Make_ID);
db_factory.selectVehicleMasterData('select ModelId,Model from tbl_vehicle WHERE MakeId ="' + $scope.memberdetailData.selected_Make_ID + '";', function (res) {
console.log("this is respo");
//console.log(res);
$scope.memberdetailData.Vehicle_Model = null;
$scope.memberdetailData.Vehicle_Model = res;
console.log($scope.memberdetailData.Vehicle_Model);
// console.log($scope.memberdetailData.Vehicle_Model);
$scope.memberdetailData.selected_Model = null;
$scope.memberdetailData.selected_Model = $scope.memberdetailData.Vehicle_Model[0].ModelId;
}, function () {
// globalFactory.showAlert('Data Error', 'No Salutation Master Found, Kindly Sync Salutation Master');
});
}
DBFactory -
db_factory_obj.selectVehicleMasterData = function (query, callBack, errorcall) {
var result = [];
db_factory_obj.db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, rs) {
for (var i = 0; i < rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
MakeId: row['MakeId'],
Make: row['Make'],
ModelId: row['ModelId'],
Model: row['Model']
}
}
////console.log(result);
callBack(result); // <-- new bit here
}, errorcall);
});
}
Please help.
Thanks.
Krunal

How to send value to div element with javascript in cordova android (sqlite)?

I am using Phonegap sqlite.
I have one table in my database named "database" in which I have 3 columns.id,data,data_num
I wanted to fetch all data from database and show it in html div.This is what I came up with:
Script:
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function refresh() {
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
var name=document.forms["frm1"]["name"].value;
var id=document.forms["frm1"]["id"].value;
var sal=document.forms["frm1"]["sal"].value;
db.transaction(function(tx) {
tx.executeSql("SELECT data from test_table;", [], function(tx, res) {
var len = results.rows.length;
var databit;
if(len>0)
{
for (var i = 0; i < len; i++)
{
databit=results.rows.item(0)['data']);
}
}
document.getElementById("data").innerHTML=databit;
});
});
</script>
HTML
<input type="button" value="Refresh" onClick="return refresh()">
<div id="data"></div>
But it does'nt work as subjected.
NOTE:This is code snippet.Assume all undeclared variable as declared.

Categories

Resources