taking values separately using local storage in html5 - html

I am making an app in html5.It is like a quiz based app. I am randomly fetching questions from the XML and displaying it one by one.I am using page navigation for that. After completing and submitting your answer u will switch to other page.if once i submit my answer i cannot attempt it back. but i can see the feedback and score on switching to that page that is my problem. I have display that feedback and score and to store it in local storage. i am able to do local storage but values that i am getting is overriding. so i am getting last submitted value.Now my concern is to divide that values navigation number wise.right now what is happening if i submit my answer and suppose i am at navigation number 3 n i am looking at navigation part 1 then there also i am getting last submitted value not the part 1 value.Please give ur suggestion and help me out for that.
Here is the code snippet:
//for navigation of pages
$(document).ready(function (){
/*$(document).bind("contextmenu",function(e){
return false;
});*/
var obj;
total=x.length;
for(var j=0;j<x.length;j++)
{
if(j==0)
{
$("#navigationlist").append('<li>'+(j+1)+'</li>');
display_nav(j,$("#selected_link"))
}
else
$("#navigationlist").append('<li>'+(j+1)+'</li>');
}
$("#next").bind("click",function (){
$(".navg").each(function(index){
if($(".navg").length==(i+1))
{
if(index==0)
obj=$(this);
}
else
{
if(index==(i+1))
obj=$(this);
}
});
for(var j=0;j<xmlDoc.getElementsByTagName("question").length;j++)
{
xmlDoc.getElementsByTagName("question")[j].removeAttribute("status");
}
$("#btnSubmit").attr("disabled","false");
$("#btnSubmit").attr("onclick","checekAnswer()");
display_nav(0,obj)
}
else
display_nav((i+1),obj)
});
});
and
correctAnswers++;
localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
$("#feedback").append(score[0].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
}
else
{
//var val = [];
//val.push(feedback[0].childNodes[0].nodeValue);
//localstorage.setItem('feedback', JSON.stringify(val));
//localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
//alert(localStorage.getItem("feedback"));
/*var v={"test":feedback[0].childNodes[0].nodeValue};
localStorage.setItem('feedback',v);
alert(localStorage.getItem('feedback'));*/
scores1.push(feedback[0].childNodes[0].nodeValue);
localStorage.setItem("highscores",JSON.stringify(scores1));
var scores = localStorage.getItem("highscores");
alert(scores);
scores = JSON.parse(scores);
alert(scores[0]);
$("#feedback").html(score[1].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
$("#feedback").append("hello");
}
//$("#counter").html("left="+xPos+",top="+yPos);
$("#trFeedBack").show("slow");
display_nav(j,obj)
}
} // end function

If I understand your question, your problem is to store items with same name but related to different pages.
LocalStorage being defined by domain, and not by page, you must change the keys you use. The usual solution is to prefix the names you want.
For example :
localStorage['pages.12.feedback'] = "the feedback I'm giving related to page 12";
localStorage['global.feedback'] = "the feedback I'm giving related to the global site";
(you'll notice I use the short notation, that I find more readable that using setItem)

Related

Is there a better way to get data from localStorage after storing the data without refreshing/reloading the page

I'm trying to make a button that could store the data to the localStorage. After storing the data, I want to get the data without refreshing/reloading the page
The way I use to fix this case is, I put 2 commands on a button. The first command is to store the data, and the second command is to get the data using $scope to make it easy to display it on the page
Here is my code
$scope.storeData = function(){
if(localStorage.getItem('value') === null){
// The value that will set to the localStorage
$scope.data = 'Selamat sore';
// To set the value on $scope.data to localStorage
localStorage.setItem('value', JSON.stringify($scope.data));
//To get the value and display it on the page
$scope.getData = JSON.parse(localStorage.getItem('value'));
}else{
$scope.getData = JSON.parse(localStorage.getItem('value'));
}
}
It's actually working, but maybe there is a better way to do this
Thanks
I find this cleaner, and simpler.
function MyController($scope) {
// if value is null a default 'Selamat sore' is set
$scope.data = localStorage.getItem('value') || 'Selamat sore';
$scope.saveData = function() {
localStorage.setItem('value', JSON.stringify($scope.data));
}
}

Wixcode "static" html iframe

Apologies if this is not the correct place to post this. I'm completely new to HTML and such, but I wanted to put a button on my website which would remember how many times it been pressed and each time someone presses it it give you a number, say for example the next prime number. With enough googleing I managed to put together some (what I expect is really bad code) which I thought could do this. This is what I have (sorry if its not formatted correctly, I had trouble with copy pasting).
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
function isPrime(_n)
{
var _isPrime=true;
var _sqrt=Math.sqrt(_n);
for(var _i=2;_i<=_sqrt;_i++)
if((_n%_i)==0) _isPrime=false;
return _isPrime;
}
function nextPrime(_s,_n)
{
while(_n>0)if(isPrime(_s++))_n--;
return --_s;
}
var clicks = 0;
function hello() {
clicks += 1;
v = nextPrime(2,clicks);
document.getElementById("clicks1").innerHTML = clicks ;
document.getElementById("v").innerHTML = v ;
};
</script>
<button type="button" onclick="hello()">Get your prime</button>
<p>How many primes have been claimed: <a id="clicks1">0</a></p>
<p>Your prime: <a id="v">0</a></p>
</body>
The problem is that when I put this code in a iframe on my wixsite it seems to reload the code each time you look at the site, so it starts the counter again. What I would like it say the button has been pressed 5 times, it will stay at 5 until the next visitor comes along and presses it. Is such a thing possible?
You don't actually need an iframe for that, You can use wixCode to do that. WixCode let's you have a DB collection. and all you need to do is update the collection values on every click.
Let's say you add an Events collection can have the fields:
id, eventName, clicksCount
add to it a single row with eventName = 'someButtonClickEvent' and clicksCount = 0
Then add the following code to your page:
import wixData from 'wix-data';
$w.onReady(function () {});
export function button1_click(event) {
wixData.get("Events", "the_event_id")
.then( (results) => {
let item = results;
let toSave = {
"_id": "the_event_id",
"clicksCount": item.clicksCount++
};
wixData.update("Events", toSave)
})
}
now you need to add button1_click as the onClick handler of your button (in the wixCode properties panel).

Problems trying to display JSON data in a django-tables2 table

I have django-tables2 set up and working well. I have set my table to be able to update checkbox columns directly from the displayed list. However when my displayed table paginates and I update a value it refreshes the entire page thus sending me back to the first page and I then have to click 'next' to get back to where I was. So I thought it might be a good idea to throw knockout.js into the mix to bind my individual columns to the corresponding data in my postgres database. According to the blurb this would allow me to simply refresh the item clicked on without having to refresh the entire page. I read the tutorial for knockout.js and all seems great and exactly what I am looking for. I've modified my views and written my js file etc and I am almost there. I have the JSONResponse from my views.py returning the correct number of rows, however, my django-tables2 tables are rendering each record as a header (ie th) in my table instead of the data as a row (ie td). Feeling like I've fallen at the last hurdle, I was wondering if anyone can shed any light on how I can fix this last bit of the puzzle please.
view.py
def mydatalist(request):
data = []
user = get_current_user()
query = Q(user_fkey=user.id)
query.add(Q(deleted__isnull=True), Q.AND)
query.add(Q(master=True), Q.AND)
tasks = Task.objects.filter(query)
for task in tasks:
data.append({"code":task.code, "name":task.name, etc})
return JsonResponse(data, safe=False)
my .js file
function Task(data) {
this.code = ko.observable(data.code);
this.name = ko.observable(data.name);
etc
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
$.getJSON('http://myweb.org/tasks/mydatalist/', function (data) {
if(data){
var mappedTasks = $.map(data, function (item) {
return new Task(item);
});
} else {
alert('data empty!');
}
self.tasks(mappedTasks);
});
}
ko.applyBindings(new TaskListViewModel());
my django-tables2 tables.py file
class MasterTable(ColumnShiftTable):
code = tables.Column(attrs={'th':{'class':'centered nodec'}})
name = tables.LinkColumn(attrs={'th':{'class':'centered nodec'}})
etc
class Meta:
model = Task
fields = ('code','name', etc)
template_name = 'django_tables2_column_shifter/bootstrap3.html'
attrs={'id':'masterlist', 'class': 'table table-noborder', 'data-bind': 'foreach: tasks, visible: task().length > 0'}
row_attrs={'id': lambda record: record.pk}
So basically everything is kind of working except that when rendered, my django-tables2 table is rendering 11 headers and no data rows instead of 1 header and 10 data rows.
If anyone can shed any light I really would appreciate it or alternatively if someone can suggest another way to achieve not having to refresh the entire page each time, that would be great also.

Set marker visible with knockout JS ko.utils.arrayFilter

Hello guys I am trying to create an app that sets the appropriate markers visible when a knockout search is being done.
Basically the app is.
When someone does a search the list that is bellow it, filters the list and makes only the markers that are associated with the filter list visible on the map.
I have created a ko.utils.arrayFilter and I am trying to set only the item.marker.setVisible(true)
My Github link is https://github.com/Aimpotis/map3
Thank you again and much respect to the community it is helping me learn a lot
All you need is to set the visibility of the marker to match whether it is found:
if (!filter) {
// this is new
ko.utils.arrayForEach(self.listLoc(), function (item) {
item.marker.setVisible(true);
});
return self.listLoc();
} else {
return ko.utils.arrayFilter(self.listLoc(), function(item) {
var result = (item.title.toLowerCase().search(filter) >= 0)
item.marker.setVisible(result); // this is a new line
return result;
});
}
Working fiddle.
Note: unless you're supporting particularly old browsers, you can use the Array filter method rather than Knockout's arrayFilter util, and .foreach instead of arrayForEach.

Getting Current Data from KendoUI TreeView

I'm using a kendo UI tree with a remote data source from a JSON file.
I have a button on the tree page which gets the current data of the tree,sends it through a POST to a server and the server saves the current data to the JSON file so as the next time I reload the page,the changes I made will be kept.That's what I want to happen.
So I know the current data of the tree is in:
$("#treeview").data("kendoTreeView").dataSource.data()
Which means the data changes real time in there for example when someone drag and drops a node of the tree.
My problem starts when this data doesn't seem to change when I drag and drop nodes inside the tree,and only changes when I drag and drop a node on the root level of the tree and even then it doesn't do it correcly as the node should be moved in there as well but instead the node gets copied,leaving the past node in the tree as well...
For Example I have this tree:
If I make a drag and drop change like this:
And I send the data,save it and reload the change isn't made at all!
PS:Even when I view the current data after the change before sending it,I see that there is no change on the data at all even though I did a change visualy with a drag and drop.So it doesn't have to do with the sending,saving and the server.
On the other hand,if I make a change like this:
I can see in the current data that the moved node is added in the end of the data indeed but it is not deleted from it's initial position within the data!So if i send the current data to the server,save it and then refresh I get the result:
The code for viewing and sending the data is:
function sendData() {
var req = createRequest();
var putUrl = "rest/hello/treeData";
req.open("post", putUrl, true);
req.setRequestHeader("Content-type","application/json");
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
alert(JSON.stringify(dsdata));
req.send(JSON.stringify(dsdata));
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
Is this a Bug or am I doing something wrong?Has anyone been able to see the current data changing correctly on every drag and drop?
First and most important you have to use the latest version of KendoUI (Kendo UI Beta v2012.3.1024) still in beta but is where they have solved many problems.
Then, when you create the kendoTreeView you have to say something like:
tree = $("#treeview").kendoTreeView({
dataSource :kendo.observableHierarchy(data),
dragAndDrop:true
}).data("kendoTreeView");
Here the important is not using directly data array but wrapping it with kendo.observableHierarchy.
Then you will have the data updated with the result of drag & drops.
For me in addition to OnaBai answer I had to use the sync function on the save method. I am using Type Script.
this.treeData = new kendo.data.HierarchicalDataSource({
data: kendo.observableHierarchy([]),//Thanks OnaBai
schema: {
model: {
id: "MenuItemId",
children: "MenuItemChildren",
hasChildren: (e) => {
//this removes arrow next to items that do not have children.
return e.MenuItemChildren && e.MenuItemChildren.length > 0;
}
}
}
});
public save() {
this.treeData.sync().done(() => {
console.log("sync data");
var myType = this.treeData.view();
this.$http.post("/api/TreeViewPicker", myType)
.then((response) => {
});
});
}