Giter Site home page Giter Site logo

knadh / localstoragedb Goto Github PK

View Code? Open in Web Editor NEW
810.0 37.0 127.0 135 KB

A simple database layer for localStorage and sessionStorage for creating structured data in the form of databases and tables

Home Page: http://nadh.in/code/localstoragedb

JavaScript 98.10% HTML 1.90%

localstoragedb's Introduction

localStorageDB 2.3.2

localStorageDB is a simple layer over localStorage (and sessionStorage) that provides a set of functions to store structured data like databases and tables. It provides basic insert/update/delete/query capabilities. localStorageDB has no dependencies, and is not based on WebSQL. Underneath it all, the structured data is stored as serialized JSON in localStorage or sessionStorage.

Installation

NPM

npm install localstoragedb

Yarn

yarn add localstoragedb

Bower

bower install localstoragedb

Run Test Cases

bower install # install mocha and chai for running test cases

open test/local_storage_db_test.html in Browser to check the result

Supported Browsers

Browsers need to support "Local Storage" in order to make localeStorageDB working.

  • IE 8<
  • Firefox 31<
  • Chrome 31<
  • Safari 7<
  • iOS Safari 7.1<
  • Android Browser 4.1<
  • Chrome for Android 42<

Usage / Examples

Creating a database, table, and populating the table

// Initialise. If the database doesn't exist, it is created
var lib = new localStorageDB("library", localStorage);

// Check if the database was just created. Useful for initial database setup
if( lib.isNew() ) {

    // create the "books" table
	lib.createTable("books", ["code", "title", "author", "year", "copies"]);

	// insert some data
	lib.insert("books", {code: "B001", title: "Phantoms in the brain", author: "Ramachandran", year: 1999, copies: 10});
	lib.insert("books", {code: "B002", title: "The tell-tale brain", author: "Ramachandran", year: 2011, copies: 10});
	lib.insert("books", {code: "B003", title: "Freakonomics", author: "Levitt and Dubner", year: 2005, copies: 10});
	lib.insert("books", {code: "B004", title: "Predictably irrational", author: "Ariely", year: 2008, copies: 10});
	lib.insert("books", {code: "B005", title: "Tesla: Man out of time", author: "Cheney", year: 2001, copies: 10});
	lib.insert("books", {code: "B006", title: "Salmon fishing in the Yemen", author: "Torday", year: 2007, copies: 10});
	lib.insert("books", {code: "B007", title: "The user illusion", author: "Norretranders", year: 1999, copies: 10});
	lib.insert("books", {code: "B008", title: "Hubble: Window of the universe", author: "Sparrow", year: 2010, copies: 10});

	// commit the database to localStorage
	// all create/drop/insert/update/delete operations should be committed
	lib.commit();
}

Creating and populating a table in one go

	// rows for pre-population
	var rows = [
		{code: "B001", title: "Phantoms in the brain", author: "Ramachandran", year: 1999, copies: 10},
		{code: "B002", title: "The tell-tale brain", author: "Ramachandran", year: 2011, copies: 10},
		{code: "B003", title: "Freakonomics", author: "Levitt and Dubner", year: 2005, copies: 10},
		{code: "B004", title: "Predictably irrational", author: "Ariely", year: 2008, copies: 10},
		{code: "B005", title: "Tesla: Man out of time", author: "Cheney", year: 2001, copies: 10},
		{code: "B006", title: "Salmon fishing in the Yemen", author: "Torday", year: 2007, copies: 10},
		{code: "B007", title: "The user illusion", author: "Norretranders", year: 1999, copies: 10},
		{code: "B008", title: "Hubble: Window of the universe", author: "Sparrow", year: 2010, copies: 10}
	];

	// create the table and insert records in one go
	lib.createTableWithData("books", rows);

	lib.commit();

Altering

// If database already exists, and want to alter existing tables
if(! (lib.columnExists("books", "publication")) ) {
	lib.alterTable("books", "publication", "McGraw-Hill Education");
	lib.commit(); // commit the deletions to localStorage
}

// Multiple columns can also added at once
if(! (lib.columnExists("books", "publication") && lib.columnExists("books", "ISBN")) ) {
	lib.alterTable("books", ["publication", "ISBN"], {publication: "McGraw-Hill Education", ISBN: "85-359-0277-5"});
	lib.commit(); // commit the deletions to localStorage
}

Querying

query() is deprecated. Use queryAll() instead.

// simple select queries
lib.queryAll("books", {
	query: {year: 2011}
});
lib.queryAll("books", {
	query: {year: 1999, author: "Norretranders"}
});

// select all books
lib.queryAll("books");

// select all books published after 2003
lib.queryAll("books", {
	query: function(row) {    // the callback function is applied to every row in the table
		if(row.year > 2003) {		// if it returns true, the row is selected
			return true;
		} else {
			return false;
		}
	}
});

// select all books by Torday and Sparrow
lib.queryAll("books", {
    query: function(row) {
            if(row.author == "Torday" || row.author == "Sparrow") {
		        return true;
	        } else {
		        return false;
	    }
    },
    limit: 5
});

Sorting

// select 5 rows sorted in ascending order by author
lib.queryAll("books", { limit: 5,
                        sort: [["author", "ASC"]]
                      });

// select all rows first sorted in ascending order by author, and then, in descending, by year
lib.queryAll("books", { sort: [["author", "ASC"], ["year", "DESC"]] });

lib.queryAll("books", { query: {"year": 2011},
                        limit: 5,
                        sort: [["author", "ASC"]]
                      });

// or using query()'s positional arguments, which is a little messy (DEPRECATED)
lib.query("books", null, null, null, [["author", "ASC"]]);

Distinct records

lib.queryAll("books", { distinct: ["year", "author"]
                      });

Example results from a query

// query results are returned as arrays of object literals
// an ID field with the internal auto-incremented id of the row is also included
// thus, ID is a reserved field name

lib.queryAll("books", {query: {author: "ramachandran"}});

/* results
[
 {
   ID: 1,
   code: "B001",
   title: "Phantoms in the brain",
   author: "Ramachandran",
   year: 1999,
   copies: 10
 },
 {
   ID: 2,
   code: "B002",
   title: "The tell-tale brain",
   author: "Ramachandran",
   year: 2011,
   copies: 10
 }
]
*/

Updating

// change the title of books published in 1999 to "Unknown"
lib.update("books", {year: 1999}, function(row) {
	row.title = "Unknown";

	// the update callback function returns to the modified record
	return row;
});

// add +5 copies to all books published after 2003
lib.update("books",
	function(row) {	// select condition callback
		if(row.year > 2003) {
			return true;
		} else {
			return false;
		}
	},
	function(row) { // update function
		row.copies+=5;
		return row;
	}
);

Insert or Update conditionally

// if there's a book with code B003, update it, or insert it as a new row
lib.insertOrUpdate("books", {code: 'B003'}, {	code: "B003",
						title: "Freakonomics",
						author: "Levitt and Dubner",
						year: 2005,
						copies: 15});

lib.commit();

Deleting

// delete all books published in 1999
lib.deleteRows("books", {year: 1999});

// delete all books published before 2005
lib.deleteRows("books", function(row) {
	if(row.year < 2005) {
		return true;
	} else {
		return false;
	}
});

lib.commit(); // commit the deletions to localStorage

Methods

Method Arguments Description
localStorageDB() database_name, storage_engine Constructor
- storage_engine can either be localStorage (default) or sessionStorage
isNew() Returns true if a database was created at the time of initialisation with the constructor
drop() Deletes a database, and purges it from localStorage
tableCount() Returns the number of tables in a database
commit() Commits the database to localStorage. Returns true if successful, and false otherwise (highly unlikely)
serialize() Returns the entire database as serialized JSON
tableExists() table_name Checks whether a table exists in the database
tableFields() table_name Returns the list of fields of a table
createTable() table_name, fields Creates a table
- fields is an array of string fieldnames. 'ID' is a reserved fieldname.
createTableWithData() table_name, rows Creates a table and populates it
- rows is an array of object literals where each object represents a record
[{field1: val, field2: val}, {field1: val, field2: val}]
alterTable() table_name, new_fields, default_values Alter a table
- new_fields can be a array of columns OR a string of single column.
- default_values (optional) can be a object of column's default values OR a default value string for single column for existing rows.
dropTable() table_name Deletes a table from the database
truncate() table_name Empties all records in a table and resets the internal auto increment ID to 0
columnExists() table_name, field_name Checks whether a column exists in database table.
rowCount() table_name Returns the number of rows in a table
insert() table_name, data Inserts a row into a table and returns its numerical ID
- data is an object literal with field-values
Every row is assigned an auto-incremented numerical ID automatically
query() DEPRECATED table_name, query, limit, start, sort
queryAll() table_name, params{} Returns an array of rows (object literals) from a table matching the query.
- query is either an object literal or null. If query is not supplied, all rows are returned
- limit is the maximum number of rows to be returned
- start is the number of rows to be skipped from the beginning (offset)
- sort is an array of sort conditions, each one of which is an array in itself with two values
- distinct is an array of fields whose values have to be unique in the returned rows
Every returned row will have it's internal auto-incremented id assigned to the variable ID
update() table_name, query, update_function Updates existing records in a table matching query, and returns the number of rows affected
- query is an object literal or a function. If query is not supplied, all rows are updated
- update_function is a function that returns an object literal with the updated values
insertOrUpdate() table_name, query, data Inserts a row into a table if the given query matches no results, or updates the rows matching the query.
- query is either an object literal, function, or null.
- data is an object literal with field-values

Returns the numerical ID if a new row was inserted, or an array of IDs if rows were updated
deleteRows() table_name, query Deletes rows from a table matching query, and returns the number of rows deleted
- query is either an object literal or a function. If query is not supplied, all rows are deleted

Storing complex objects

While the library is meant for storing fundamental types (strings, numbers, bools), it is possible to store object literals and arrays as column values, with certain caveats. Some comparison queries, distinct etc. may not work. In addition, if you retrieve a stored array in a query result and modify its values in place, these changes will persist throughout further queries until the page is refreshed. This is because localStorageDB loads and unserializes data and keeps it in memory in a global pool until the page is refreshed, and arrays and objects returned in results are passed by reference.

If you really need to store arrays and objects, you should implement a deep-copy function through which you pass the results before manipulation.

localstoragedb's People

Contributors

a904guy avatar ashishsharma229 avatar dependabot[bot] avatar dj-raphael avatar geirsagberg avatar gustavwilliam avatar j2team avatar kkohler2 avatar knadh avatar moisesh18 avatar objectivehtml avatar patik avatar remoharsono avatar vividvilla avatar w35l3y avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

localstoragedb's Issues

Sort isn't working?

I'm attempting to sort mapId's in ascending order:

var playingServers = getDatabase().queryAll('playing', {sort: [['mapId', 'ASC']]});

console.log(playingServers);

However, it doesn't appear to be working:
screenshot on 11 17 2014 at 1 35 01 pm

As you can see, it is not sorting the mapId in ascending order, but instead by the ID. I also have no errors, so I'm not sure why it isn't working. I've looked at the docs, and it would appear that I'm doing everything correctly?

Docs incorrect with insertOrUpdate method

I have always had issues with the insertOrUpdate method working. Your code indicates the correct param order is table_name, query, data whereas the docs indicate table_name, data, query

Bug while inserting/updating null values into db

Hi,
we found an issue updating rows with null values. While an insert will save null values (examle: {a: "hello", b: null}), an update will remove the field with null as value (example: {a: "hello"}, field b does not exist any more).
After investigating the code we found out that the function validFields(), which is called during update, filters field with undefined or null values.

While we are questioning if maybe it should be possible to store null values in the database it at least seems odd that null values are inserted but removed with updates.

Suggestion:
Change the line (in function validFields)
if ((data[field] !== null && data[field] !== undefined)) {
to
if (data[field] !== undefined) {

IE not working properly with the localstoragedb.js

I use this jquery plugin in my web application: http://o.pckg.in/deals-crawler

Every browser properly works with this plugin. But IE doesn't work properly. IE throws few exception while parsing the script. When I checked the error console, I noticed that the following line is the culprit.

    // delete rows
    delete: function(table_name, query) {
        tableExistsWarn(table_name);

        var result_ids = [];
        if(!query) {
            result_ids = getIDs(table_name);
        } else if(typeof query == 'object') {

delete is a keyword. We should not ideally try to overload or expose a method with the name delete. I would prefer using another name like deleteQuery:

The above code should be changed to as follows:

    // delete rows
    deleteQuery: function(table_name, query) {
        tableExistsWarn(table_name);

        var result_ids = [];
        if(!query) {
            result_ids = getIDs(table_name);
        } else if(typeof query == 'object') {

After I made this change, it worked like charm.

-Thanks
Sankar.

Not proper database taking during queryAll

I do queryAll for table A and it returns table B data.
i have tables A,B,C. table B has foreign key .
Is this something with copying by reference or by value?
queryAll('A',{ query: {var_id:n.id}); - returns B rows
queryAll('A',{}); - returns proper A rows.
Is this bug?
Version 2.3.1

Firefox storing localstorage database as string

Hey guys!

Just recently checked through Firebug how the library works on Firefox, and the object is being stored as a string (surrounded by double quotes), instead of an object e.g.: "{}" instead of {}, rendering the library unusable.

Is there anything we can do?

TypeError: row[field] is null at localstoragedb.js (line 137)

Example code to reproduce the error:

var lib = new localStorageDB("library2");
if( lib.isNew() ) {
lib.createTable("books", ["code", "title", "author", "year", "copies"]);
}
lib.insertOrUpdate("books", {code: 'B003'}, {code: "B003",title: "Freakonomics",author: "Levitt and Dubner",year: 2005,copies: 15});
lib.commit();

ability to use other Storage objects

I think it would be a good idea to add an option to choose other storage object to work with.
I would like to use localStorageDB with sessionStorage object or Firefox's simpleStorage object instead of hardcoded localStorage object.
Of course localStorage should be default object to use if no replacement object provided.

limit before sorting

Hi,

I've found a critical bug in your lib. If you query data using a limit, you sort the result after limiting it. E.g

  1. A Table has 10 entries.
  2. query(table, limit: 5, sort: asc) //not real code, just for instance..
  3. you sort the first 5 rows which I get.

The correct behaviour would be to sort the whole entries before you limit the result.

Testing db integrity

As some point I've made a mistake in my app and the db has become corrupt and I get a warning in the the console.

'unexpected string'

You can simulate this by just manually removing one of the characters.

Is there a best way to test and possibly fix the integrity of the database?

Not supporting cross-tabs

Hi,

Currently it is only supporting same page/tab, but not working in multiple tabs for same pages/application. Now days, it is a basic use case that users would open same app on multiple tabs.

Please update me if this can be accommodated.

  • Thanks

should be AND instead of OR by default

Current behavior of lib.query is counter-intuitive.
Example:
lib.query("books", {year: 1999, author: "Norretranders"});

Line above currently works like this:
SELECT * FROM books WHERE year=1999 OR author='Norretranders';

I think it should work like this:
SELECT * FROM books WHERE year=1999 AND author='Norretranders';

insertOrUpdate - Cannot read property 'toString' of null

I'm trying to use insertOrUpdate and I'm getting the error:

Cannot read property 'toString' of null

I'm using the following code;

lib.insertOrUpdate("settings", {name: 'sound'}, {
name: "sound",
gameState: "0",
desc: "Turns sound on and off"
});

What am I doing wrong please?

Setting the column names in queryAll ()

Is there a way to define the name of the columns that are returned in queryAll ()?

LIke this: db.queryAll("table_name", {'columns': ['Colum A', 'Colum B', 'Colum C']});

Case Insensitive Sort

It appears that the sort is case sensitive. Is there any way to make that case insensitive?

Check if a commit is successful

Please correct me if I'm wrong, but I don't see anywhere in the documentation to check if a commit has been successful. Is this possible? As of now, commit() returns 'undefined' but it would be really useful if it was possible to get at least a boolean value as to the result of the commit.

P.S. I just discovered localStorageDB today and, as a novice, it was incredible easy to pick up. I'm very interested in using localstorage to experiment with some personal projects and am excited in the prospect of using this to make it that much easier. Thanks for this great resource!

Query Question

Hi knadh,

I am trying to implement your localStorageDB and have created a database. When I run the following query:

db.query("senators", function(row) { // the callback function is applied to every row in the table
if(row.chamber == "upper" && row.geoid10 == geo_id) { // if it returns true, the row is selected
return true;
} else {
return false;
}
});

How do I retrieve the results? I can watch the query loop and it returns true on one of the records but I don't understand where the results are stored in order to display them on my page?

Should I create an array and add each record to that array each time it returns true? Or do you have a function I need to call that will display results for all rows returned the way you mention in your README File?

queryAll query returns Cannot read property 'toString' of null

Hi,

if the local database contains a null value for a property used by the queryAll query, it generates an exception.

var lib = new localStorageDB("carc", localStorage);
            if(!lib.tableExists("settings")) {
              lib.createTable("settings", ["name", "gameState", "desc"]);
              lib.insert("settings", {name: null,gameState: "maingame", desc: "sets the current game state"});
              lib.insert("settings", {name: "slidertype",gameState: "0",desc: "sets slider type 0 = slider 1 = buttons"});
              lib.insert("settings", {name: "sound", gameState: "0", desc: "Turns sound on and off"});
              lib.commit();
            }
            var searchObject = {name:"slidertype"}
            console.log(lib.queryAll("settings",{query:searchObject}));

-> Cannot read property 'toString' of null

null values should simply be filtered out of the returned array

Can be fixed by simply adding row 253:

if(!row[field]){
            exists = false;
            break;
          }

I can also do a pull request if needed

Thanks

Better type checking for updates

This code updates all the records instead of none:

db.insertOrUpdate("table", { field: 0 }, { 'field': 5 });

The issue should be on validFields() function, where you are doing a "simple" if(data[field]) instead of a type checking.

How can I query all items?

At the first, very nice project, clean API, really, really nice to work with.

My question: How to query all items in table, I mean how to use 'query' function with no condition specified? I 'm just currently using this:
lib.query("books",{return true})
... not sure if there is some easiest way ... something like lib.query("books") ???

Improper use of for..in

Hi,

I was porting an existing Javascript program to Windows 8 (Metro). I came across an issue that I wanted to bring to your notice.

The localStorageDB code has a few places where a for.. in loop is used to iterate through arrays. The issues I was facing were fixed when I changed these to a regular for loop. I thought I could bring this to your notice so you could fix it in the code. The for..in loop is meant to loop through properties of an object.
http://www.w3schools.com/js/js_loop_for_in.asp

Here are some references with explanations on why it shouldn't be used to loop through arrays:
http://blog.sebarmeli.com/2010/12/06/best-way-to-loop-through-an-array-in-javascript/
http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript

Thanks for sharing localStorageDB with all of us. Hope this helps make it better!

Ralston

Migrate database when update schema?

I already had a table by run the code db.createTable('auth', ['username', 'password']) in the first deployment. The table 'auth' already have data.
And I want to add 2 more columns like 'full_name' and 'avatar_link' into that table without dropping and creating it.
How can I do that?

sort:[[]] always sorts by ID and Ascending order

Hi all,

It seems to sort only by ID, no matter what you enter in the sort field. The following is the query format I used :
lib.queryAll("SearchHistory", { limit: limit, sort: [["viewCount", "DESC"]]});

viewCount is an integer value, I also tested with string values.

Any ideas? Is there something I'm doing wrong?

I tested in the Chrome Developer Console, web page running on iPhone, iPad, BlackBerry Q10 and Windows desktop clients.

distinct in query

Hello

Is there a way to do a 'distinct' query?

I have a table that contains many many rows and only a few types and would like to know which types are in there.

so something like

select distinct(type) from table

dan

createTable and last item not stored in DB

I'm using the latest version and founfdout following:

I created table like this:
lib.createTable("car", ["place","km","km1"]);

... and inserted items like this:
lib.insert("car",{place:'aaa', km:1256321,km1:958896})

... and it inserts only fields place and km into store. I tried this and that and found out, that the last field in createTable definition is not inserted. Current workarround is to add some spare field into createTable command(as the last one), so all my fields are inserted correctly ...

Changelog

Hey there, I use this library quite a bit. Just wondering if you have an official changelog from each version? If not, I think this would be a great addition to the library.

GroupBy SQL Query

This plugin is nice to use. But I want to know how to implement group by statement in SQL query.

Is there a way how to flush the library cache?

While testing in Chrome I can update the localStorage values using chrome developer tools. But such changes are not visible back in your library. For example, while testing, I'm changing some values in Chrome dev tool in localstorage (values stored by your tool), but using library.query(...) I'm still getting the former values, not the one actualy available in localStorage in my browser. Its seams to me, that you keep values in some cache. Is there a way how to flush the cache and let query command really query the locaStorage?

Thank you for such a great tool !!!

tableExists() not working properly.

When I execute lib.tableExists(tableName), it doesn't not return proper result. Even when I have created a table, it returns false.

Fix for this:

    // check whether a table exists
    tableExists: function(table_name) {
        return tableExists();
    },

This should be:

    // check whether a table exists
    tableExists: function(table_name) {
        return tableExists(table_name);
    },

As shown above, the table_name should be passed properly to the underlying private function.

-Thanks
Sankar.

Unit Test ?

I noticed currently this project did not have any test.
Could I send a pull request to add some test cases for this project ?

Missing comma on line 372

Don't have time to make a proper pull request. Just FYI, this lib is great. I use it a lot and taught it to my students in a mobile application class at a college I worked last year.

Anyway... on line 372 on the unminified version is missing a comma. Also, do you have a changelog of what has changed in 2.1?

deleteRows() method: Deleting rows of the results that were queried before.

I have queried the result in this step:
"
var negativeQueryResult = localDatabase.queryAll("localPuzzleDatabase", {
query: function (row) {
if (row.type == "negative") {
return true;
} else {
return false;
}
},
limit: 1
});
"

And I would like to delete the row of queried result from the localStorage database. I am wondering what is the best approach of doing that?

I am currently using this step but it does not seem to work:

"
localDatabase.deleteRows("localPuzzleDatabase", {negativeQueryResult});
localDatabase.commit();
"

search values in array

Hi i have case i inserted the array on db and now to search by key within array but unable to it ,giving toString error

Distinct query bug

lib.queryAll("books", { distinct: ["year", "author"]});

I have used DomSQL.queryAll("prodlist", { distinct: ["pName", "pLocalName", "pImage2"]});
where pName and pLocalName are having spaces and pImage2 may or may not be distinct alone
eg.
record 1: Orange small, Orange small, org.jpg
record 2: Orange large, Orange large, org.jpg
record 3: Sweet Lime, Sweet Lime, org.jpg

return data fails to provide all three records
Note: data is to explain the case and has no literal meaning

Thanks for good work

IE7-8 commit issue

The library does not seem to retain commit on IE7-8
After commit, the rowCount increases, but refresh causes it to become emptied.

return false in queryAll

I'm using localstoragedb for my local database, till now whatever I've done is working correct. But on submitting one of form return false doesn't stop submitting the form. Here is the code.....

$("#registration").on("submit", function(e){
     e.preventDefault();
      if($('#username').val() === ''){
         $('#username').parent().addClass('error');
    return false;     
};
if($('#password').val() === ''){
   $('#password').parent().addClass('error');
   return false;     
};
if($('#mobile').val() === ''){
   $('#mobile').parent().addClass('error');
   return false;     
};

localDb.queryAll("UserInfo");
localDb.queryAll("UserInfo", {
    query:function(row) {    
if(row.username === $('#username').val()) {  
        alert("username already existed");
         return false;
    }

}

 });


  localDb.insert("UserInfo", {username: $('#username').val(), password: 
  $('#password').val(), Mobile: $("#mobile").val()}); 
  localDb.commit();
  $(".message").show();
  setTimeout(function () {
                window.location.replace("login.html");
             }, 2000);

  });

All the return false work correctly except inside localDb.queryAll function. It will alert me username already existed but submitted the form also. Look like some problem with return false. Is something i'm missing or doing wrong?????

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.