How to get the Ids of checkbox I've checked? - javascript

I tried the below code,
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://static.jstree.com/v.1.0pre/jquery.js"></script>
<script type="text/javascript" src="http://static.jstree.com/v.1.0pre/jquery.jstree.js"></script>
</head>
<body>
<div id="jstree_id" class="demo">
<ul>
<li id="asia">
asia
<ul>
<li id="china">
india
</li>
<li id="japan">
japan
</li>
</ul>
</li>
<li id="usa">
usa
</li>
</ul>
</div>
<input type="text" id="com" onKeyUp="bridge('com_url','my_id')" />
<input type="text" id="person" onKeyUp="bridge('prsn_url','my_id')" />
<input type="button" value="click" onClick="bridge('url','my_id');" />
<script type="text/javascript" class="source">
$(function () {
$("#jstree_id").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "sort", "ui" ]
});
});
function bridge(path, tag) {
// path & tag are required one for Ajax functions*
var checked_ids = [];
$("#jstree_id").jstree("get_checked",null,true).each(function () {
checked_ids.push(this.id);
});
var company = $("#com").val() || [];
var person = $("#person").val() || [];
console.log(company+person+checked_ids);
}
</script>
</body>
</html>
The question is:
When I click on the checkbox it returns only the ids Iv'e already checked. How do I get the ids of currently checked checkboxes?
My whole purpose of the code is to search the database against all combination of checkbox tree and text through Ajax.

Instead of using js events, it's best to use the native events supported by jstree:
<body>
<div id="jstree_id" class="demo">
<ul>
<li id="asia">
asia
<ul>
<li id="china">
india
</li>
<li id="japan">
japan
</li>
</ul>
</li>
<li id="usa">
usa
</li>
</ul>
</div>
<input type="text" id="com" onKeyUp="bridge('com_url','my_id')" />
<input type="text" id="person" onKeyUp="bridge('prsn_url','my_id')" />
<input type="button" value="click" onClick="bridge('url','my_id');" />
<script type="text/javascript" class="source">
$(function () {
$("#jstree_id").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "sort", "ui" ]
});
});
$('#jstree_id').bind('change_state.jstree',function(){
bridge('url','my_id');
});
function bridge(path, tag) {
//path & tag are required one for Ajax functions
var checked_ids = [];
$("#jstree_id").jstree("get_checked",null,true).each(function () {
checked_ids.push(this.id);
});
var company = $("#com").val() || [];
var person = $("#person").val() || [];
console.log(company+person+checked_ids);
}
</script>
</body>
</html>
Using the click event directly does not work, as the jstree event which changes the states of the checkboxes fires after the click event fires

function getCheckedIDs()
{
var elements = document.getElementsByTagName("INPUT");
var checkedArray = new Array();
for(var i=0;i<elements.length;i++)
{
if(elements[i].type === 'checkbox' && elements[i].checked)
{
checkedArray.push(elements[i].id);
}
}
return checkedArray;
}
You can call this function onchange of checkboxes.

u can try this
$(document).ready(function() {
var entity=[];
$("input[type='checkbox']").click(function(){
entity = $('input:checkbox:checked[name=checked]').map(function () {
return $(this).attr("id");
}).get();
alert(entity);
});
});

Related

Why does the expression get printed along with the curly braces?

The code is supposed to print the first element in the todo app which is "Build a Todo App". It also does not include the new elements which I am adding into the app.
I have proceeded according to a tutorial and the code is exactly the same. I have cross checked it many times but my app still displays {{todo.title}} instead of "Build a Todo app"
My code:
<style>
.done{text-decoration: line-through; color:#ccc;}
</style>
</head>
<body>
<div ng-controller="todoController">
<form name="frm" ng-submit="addTodo()">
<input type="text" name="newtodo" ng-model="newTodo" required />
<button ng-disabled="frm.$invalid" ng-click="addtodo()">Add</button>
</form>
<button ng-click="clearCompleted()">Clear Completed</button>
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done" />
<span ng-class="{'done':todo.done}">{{todo.title}}</span>
</li>
</ul>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script>
angular.module('ToDo', [])
ToDo.controller('todoController',['$scope', function($scope){
$scope.todos = [
{'title': 'Build a ToDo App', 'done': false}
];
$scope.addtodo = function(){
$scope.todos.push({'title': $scope.newTodo , 'done': false})
$scope.newTodo=' '
}
$scope.clearCompleted = function(){
$scope.todos = $scope.todos.filter(function(item){
return !item.done
})
}
}])
</script>
What am I doing wrong?
So, It seems there was some residual code from elsewhere. I've cleared that up.
let ToDo = angular.module('myApp', [])
ToDo.controller('todoController',['$scope', function($scope){
$scope.todos = [
{'title': 'Build a ToDo App', 'done': false}
];
$scope.addtodo = function(){
$scope.todos.push({'title': $scope.newTodo , 'done': false})
$scope.newTodo=' '
}
$scope.clearCompleted = function(){
$scope.todos = $scope.todos.filter(function(item){
return !item.done
})
}
}])
.done{text-decoration: line-through; color:#ccc;}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="todoController">
<form name="frm" ng-submit="addTodo()">
<input type="text" name="newtodo" ng-model="newTodo" required />
<button ng-disabled="frm.$invalid" ng-click="addtodo()">Add</button>
</form>
<button ng-click="clearCompleted()">Clear Completed</button>
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done" />
<span ng-class="{'done':todo.done}">{{todo.title}}</span>
</li>
</ul>
</div>
</body>
</html>
What was wrong?
There was no ToDo variable. Added let ToDo
The controller name was different from the one in the HTML
The module was named ToDo instead of myApp as in the HTML
Added ng-app to the body

Array in array, angularJS, ng-repeat

im struggling with iterating over arrays in arrays. I need to create buttonlike vertical menu and cant get it work.
angular.module('NavigationApp',[]).controller('NavigationController', function($scope) {
$scope.items = [
'Home',
'Orders':
{
orders:['Orders', 'Open', 'Closed', 'New', 'Forgotten']
},
'Users',
'Resources',
'Settings',
'Help'
];
$scope.activeMenu = $scope.items[0];
$scope.setActive = function(item) {
$scope.activeMenu = item;
};
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="NavigationApp">
<div class="col-md-3">
<div ng-controller="NavigationController">
<input type="text" placeholder="Search" ng-model="filterQuery" />
<ul class="list-group">
<li ng-click="setActive(item)" ng-class="{active: activeMenu === item}" class="btn btn-lg list-group-item" ng-repeat="item in items | filter:filterQuery">{{ item }}
</li>
</ul>
</div>
</div>
<script src="js/MainController.js"></script>
</body>
</html>
What i need to do is display array of items and while Orders item is active expand it with elements given in other array. To be honest i just dont know how to make it.
You are trying to ng-repeat over a heterogeneus array. i.e. it's elements are not all of the same type. The implementation logic needs to change here.
One thing you can do if your data structure is not flexible, is to use a typeof item === 'object' to filter out the object from the strings, or conversely check for typeof string
Here's a quick, basic example of what you could use:
$scope.items = [{
name: 'Home'
}, {
name: 'Orders',
dropdown: [{
name: 'Orders'
}]
},{
name: 'Users'
},
...
];
<li ng-repeat="item in items | filter:filterQuery" class="btn btn-lg list-group-item dropdown" ng-class="{active: activeMenu === item}" ng-click="setActive(item)">
<a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">
{{ item.name }} <span class="caret" ng-if="item.dropdown"></span>
</a>
<ul ng-if="item.dropdown" class="dropdown-menu">
<li ng-repeat="dItem in item.dropdown">
{{dItem.name}}
</li>
</ul>
</li>
I'd suggest having another indepth look at https://docs.angularjs.org/api/ng/directive/ngRepeat to fully understand the structure required by the directive.
angular.module('NavigationApp',[]).controller('NavigationController', function($scope) {
$scope.items = {
main:['Home','Orders','Users','Resources','Settings','Help'],
sub:['Open','Closed','New','Forgotten']
};
$scope.activeMenu = $scope.items[0];
$scope.setActive = function(item) {
$scope.activeMenu = item;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="NavigationApp">
<div class="col-md-3">
<div ng-controller="NavigationController">
<input type="text" placeholder="Search" ng-model="filterQuery" />
<ul class="list-group">
<li ng-click="setActive(item)" ng-class="{active: activeMenu === item}" class="btn btn-lg list-group-item" ng-repeat="item in items.main | filter:filterQuery">{{ item }}
<ul>
<li class="btn btn-lg list-group-item" ng-repeat="it in items.sub" ng-if="activeMenu === 'Orders'">{{it}}</li>
</ul>
</li>
</ul>
</div>
</div>
<script src="js/MainController.js"></script>
</body>
</html>
This is closer to what i want to achieve. But i dont know how to apply this nested UL to only one Li from parent list.
this filter work correctly
INPUT :
['Home',{ 'Orders':{orders:['Orders', 'Open', 'Closed', 'New', 'Forgotten']}},'Users','Resources','Settings','Help']
OUTPUT :
["Home", "Orders", "Open", "Closed", "New", "Forgotten", "Users", "Resources", "Settings", "Help"]
app.filter('customfilter', function () {
return function (data) {
function clean(item)
{
var result = [] ;
// check if type is array
if(Array.isArray(item)){
// parse array
item.forEach(function(i){
result = result.concat(clean(i));
})
}// check if type is opject
else if(typeof item =="object"){
// parse opject
Object.keys(item).map(function (key) {
result = result.concat(clean(item[key]));
});
}else{
result= [item]
}
return result ;
}
return clean(data) ;
}
})
I believe there are so many ways to answer this question,although I've made a sample plunker for your problem.Below is how your
HTML will look like
<body ng-app="NavigationApp">
<div class="col-md-3">
<div ng-controller="NavigationController">
<input type="text" placeholder="Search" ng-model="filterQuery" />
<ul class="list-group">
<li ng-click="setActive(item)" ng-class="{active: activeMenu === item}" class="btn btn-lg list-group-item" ng-repeat="item in items | filter:filterQuery">
<a href="#">
<p ng-hide="item.dropdown"> {{ item.name }}</p>
<p ng-show="item.dropdown" ng-repeat="values in item.dropdown"> {{ values }}</p>
</a>
</li>
</ul>
</div>
</div>
</body>
JS look like
angular.module('NavigationApp', []).controller('NavigationController', function($scope) {
var orderItemsObj = {
orders: ['Orders', 'Open', 'Closed', 'New', 'Forgotten']
};
$scope.items = [{
name: 'Home'
}, {
name: 'Orders',
dropdown: ['Orders', 'Open', 'Closed', 'New', 'Forgotten']
}, {
name: 'Users'
}, ];
$scope.activeMenu = $scope.items[0];
$scope.setActive = function(item) {
$scope.activeMenu = item;
};
});

Fancytree not visible has class ui-helper-hidden

I have just started with fancytree 2.6.0 and I am populating it from a web service request.
My problem is that all the nodes are present but are made invisible by the ui-helper-hidden class. I have put in a temporary fix with: $(rootNode.ul).removeClass('ui-helper-hidden'); but I am sure I am missing something.
The scripts and css:
<link href="Scripts/jquery-plugins/fancytree-2.6.0/src/skin-themeroller/ui.fancytree.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.11.1/jquery-1.11.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.11.1/jquery-migrate-1.2.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.11.2/jquery-ui.js" type="text/javascript"></script>
<script src="Scripts/jquery-plugins/fancytree-2.6.0/src/jquery.fancytree.js" type="text/javascript"> </script>
<script src="Scripts/jquery-plugins/fancytree-2.6.0/src/jquery.fancytree.themeroller.js" type="text/javascript"> </script>
The code:
$('#selectedClausesDiv').fancytree();
$.when(
$.getJSON("Handlers/GetQuotationHandler.ashx?jsoncallback=?", { quoteReference: quoteReference, quoteVersion: quoteVersion })
).then(function (data) {
if (data.ErrorCode == 0 && data.Quotation != null) {
var rootNode = $("#selectedClausesDiv").fancytree("getRootNode");
$.each(data.Quotation.Covers, function (index, item) {
addCover(rootNode, item);
});
// FIXME: why is this necessary ??
// $(rootNode.ul).removeClass('ui-helper-hidden');
}
});
function addCover(rootNode, cover) {
var coverId = 'selected_' + cover.BusinessClassId + '_' + cover.CoverId;
var coverNode = rootNode.addChildren({
title: cover.Name,
tooltip: "This folder and all child nodes were added programmatically.",
folder: true
});
}
The generated html:
<div class="grid_13 alpha omega" id="selectedClausesDiv">
<ul class="ui-fancytree fancytree-container ui-fancytree-source ui-helper-hidden" tabindex="0">
<li class="">
<span class="fancytree-node fancytree-folder fancytree-exp-n fancytree-ico-cf">
<span class="fancytree-expander"/>
<span class="fancytree-icon"/>
<span title="This folder and all child nodes were added programmatically." class="fancytree-title">P&I Owned</span>
</span>
</li>
<li class="fancytree-lastsib">
<span class="fancytree-node fancytree-folder fancytree-lastsib fancytree-exp-nl fancytree-ico-cf">
<span class="fancytree-expander"/>
<span class="fancytree-icon"/>
<span title="This folder and all child nodes were added programmatically." class="fancytree-title">P&I Extended Cargo</span>
</span>
</li>
</ul>
</div>
Fancytree will automatically hide the root element if no data source is provided.
If you are adding data using the API and no initial source, providing a blank source option will prevent Fancytree from hiding the root element.
$("#tree").fancytree({
source: []
});

button selector binding issue on private / public closure

I'm creating a set of JavaScript methods that will clone pre-existing HTML. Here is the HTML:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script src="lib/pm-helpers.js"></script> -->
<script src="lib/pm-ajax-inputs.js"></script>
</head>
<style>
.hidden { display: none; }
</style>
<body>
<script>
jQuery( document ).ready( function() {
/*
* Clone example
* the instance() method takes 3 parameters
* #param: wrapper id or class
* #param: clone group
* #param: action button, image or link; something with a click event ability.
*/
var instance = PM_CONTROLS.MODEL.PROPS.instance( '.first', '.control-group', '#clone' );
instance.bind();
} );
</script>
<ul class='first'>
<li class='control-group'>
<input type="text" name="discover[]" value="" placeholder="info here" />
<input type="button" id="bn-edit" class="green pm-edit" value="edit">
<input type="button" id="bn-delete" class="blue pm-delete" value='delete'>
</li>
</ul>
<ul class='second'>
<li id='control-group2' class='controls '>
<input type="text" name="discover[]" value="" placeholder="info here" />
<input type="button" id="bn-edit1" class="green pm-edit" value="farfenugal">
<input type="button" id="bn-delete1" class="blue pm-delete" value='farfenay'>
</li>
</ul>
<ul id="control-wrapper">
<li class='controls'>
<input type="text" name="discover[]" value="" placeholder="control purpose here" />
<input type="button" id="clone" class="green pm-add" value="add">
</li>
</ul>
<ul id="control-wrapper2">
<li class='controls'>
<input type="text" name="discover[]" value="" placeholder="control purpose here" />
<input type="button" id="clone1" class="green pm-add" value="add">
</li>
</ul>
</body>
Here is the JS:
var PM_CONTROLS = PM_CONTROLS || {};
PM_CONTROLS.createNS = function ( namespace ) {
var nsparts = namespace.split(".");
var parent = PM_CONTROLS;
// include or exclude the root namespace so we strip it if it's in the namespace
if (nsparts[0] === "PM_CONTROLS") {
nsparts = nsparts.slice(1);
}
// if required create a nested namespace by looping through the parts
for (var i = 0; i < nsparts.length; i++) {
var partname = nsparts[i];
// check if the current parent already has the namespace declared
// if it doesn't then create it
if (typeof parent[ partname ] === "undefined") {
parent[partname] = {};
}
// get a reference to the deepest element in the hierarchy
parent = parent[ partname ];
}
// the parent is now constructed with empty namespaces and can be used.
// we return the outermost namespace
return parent;
};
PM_CONTROLS.createNS( 'PM_CONTROLS.MODEL.PROPS');
PM_CONTROLS.createNS( 'PM_CONTROLS.ACTIONS');
PM_CONTROLS.props = null;
PM_CONTROLS.i= 0;
PM_CONTROLS.MODEL.PROPS.instance = function ( wrapper_class_or_id, element_to_clone_id, clone_button_id ) {
var props = {
wrapper : wrapper_class_or_id + PM_CONTROLS.i++
, clone : element_to_clone_id + PM_CONTROLS.i
, button : clone_button_id
};
var bind = function() {
PM_CONTROLS.props = getProps();
return new PM_CONTROLS.ACTIONS.bindAction();
};
var getProps = function() {
return props;
};
return {
bind : bind
, getProps: getProps
};
};
PM_CONTROLS.ACTIONS.clone = function() {
var clone = $( PM_CONTROLS.props.clone ).clone();
$( PM_CONTROLS.props.wrapper ).append( clone );
clone.fadeIn('fast');
};
PM_CONTROLS.ACTIONS.bindAction = function () {
$( PM_CONTROLS.props.button ).on( 'click', '', PM_CONTROLS.ACTIONS.clone() );
//$( '#clone' ).click( PM_CONTROLS.ACTIONS.clone() );
};
So when running the HTML the ul with the class='control-group' is getting loaded into the PM_CONTROLS closures and properties.
Furthermore, the code steps through everything without any errors and the values that eventually get passed to the bindAction() method are correct ( I've hard-coded the selector for debugging purposes in the bindAction code ).
Can you explain why the HTML button with the id='#clone' is not binding a click event for the instance variable that is created?
Your help is appreciated on this one.
Regards,
Steve

save text value to listview & start count the time

I have TWO main questions that I really would have help with.
I have googled and searched for some day now without any help, but if you know any links that I maybe haven't watched or any site with help, then give me.
I would appreciated it, OR if you already have the code/sample code, would help :-)
I work with PhoneGap & JQuery Mobile right now, and the thing is this.
I have a 'textarea' there you write something, then a save button, what I want it to do is that when I press the save-button, the textvalue I wrote in the textarea would get saved in a listview in another page of the app. I have looked at "localstorage" but nothing works correctly.
(Also, if you write something in textarea and you press the cancel button, the text in the textarea should be deleted next time you go in to that page.)
The second question is:
When I press the save button, it should begin to count, in seconds, minutes, hours, days.
Think of it like this. I write "toothbrush" in the textarea and press save, now when I go to the listview-page, I can see it says toothbrush in the listview, beside the text it says 1m, 5m, 1h, it just update when it was last time I bought or changed the toothbrush, so next time I open the app, I can see "TOOTHBRUSH: 4Days, 16HRS, 52MINS AGO". In that way I can check when I bought something, or changed something.
This is my codes, both html & .js, what should I do so this mission will work.
Any suggestions, sites, or code you guys have that would help?
Thank you so much.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="save">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="cancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ol data-role="listview" id="orderedList" data-inset="true"></ol>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
and my almost empty -js code.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#add', function(){
$.mobile.navigate( "#page2", { transition : "slide", info: "info about the #bar hash" });
});
});
function save ()
{
var fieldValue = document.getElementById('textarea').value;
localStorage.setItem('content', orderedList);
}
EDIT:
Here is my new html & js file, after looked at your awesome code-example, but when I run it on my phone with phonegap, still, the save, cancel, the time and even the saved text will not show up.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea id="newItemText"></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#" data-transition="slide" id="btnSave">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="btnCancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="orderedList" data-inset="true">
</ul>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And the JS file.
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + timeAgo( (new Date(TheList[i].time).getTime())/1000) + ' ago<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});
function timeAgo(time){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var diff = (new Date() - new Date(time*1000)) / 1000;
if (diff < 5) return "now";
var i = 0;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit){
var diff = Math.floor(diff / unit.in_seconds);
return diff + " " + unit.name + (diff>1 ? "s" : "");
}
};
}
SOLUTION:
The JSFiddler code-example, the demo is perfect and are based on jQuery 1.9.1 & jQuery Mobile 1.3.0b1, I used 1.6.4 & 1.1.0.
After updating this two .js files, everything worked on PhoneGap!
Here is a DEMO
There are many questions within your problem, so I will probably not manage to answer all of them. To use localStorage with an array of 'tasks' you use JSON.stringify when saving and JSON.parse when retrieving.
So, each time page3 is displayed, you retrieve the current list of items from localStorage, create list items, empty the list and then append the created items :
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + TheList[i].time + '<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
When entering a new item, you want to store the text and the current time, so use an object. First get the current list from localStorage, then create the new item and add it to the list, finally save back to localStorage clear the textarea and navigate to page3. The cancel button just clears the textarea:
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});

Categories