Ok... so a user enters info into the journal field and hits submit, and a function gets called on the information they have submitted, which I call changeTextComment(). That function calls another function and so on as the info is formatted and placed in the cue, as in a Facebook commentary.
I need this information saved so it can be recalled later, in local storage, making the app not refresh every time I restart it. So...
<script>
function appCache() {
// Check browser support
// this is experimental for local storage...
more here: http://www.w3schools.com/html/html5_webstorage.asp
if (typeof(Storage) != "undefined") {
localStorage.setItem(para);
// Retrieve
document.getElementById("journal").innerHTML = localStorage.getItem(para);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
};
</script>
So looking at the appCache function it seems like it might work except I need to identify what the key variable is that will be stored and then retrieved.
I think this is the variable userInput, as any time the user hits the 'add to journal' button this variable is used to store the user input and then put into the changeTextComment() function.
I am wondering if this is the simplest way to deal with this whole thing... I do not yet understand databases, but wondering if that would be easier to learn.
In this case, I would add the function Appcache() to the function changeText() such that it caches the variable and then how would I set it up to then feed the value of the variable's cached info into changeText() upon launch of the app?
Every submission to the journal will have a unique value.
Heres the ChangeTextComment() Function... still sorting out how to use classes in css to simplify these functions:
function changeTextComment(){
// to be modified from the above to change the location of the dump
var userInput = document.getElementById('userInput').value;
// get the input from the user
var panel = document.createElement("div"); // create a parent divider for everything
// assignment of attributes
panel.setAttribute("class","panel panel-default panel-body");
panel.setAttribute("id","panelBody");
var para = document.createElement("P");
var t = document.createTextNode(userInput);
para.appendChild(t);
// add comment area
var c = document.createElement("INPUT");
c.setAttribute("type", "text");
c.setAttribute("id", "comment");
c.setAttribute("placeholder", "comment here");
c.setAttribute("class", "form-control input-lg");
// add comment button attempt -- success <> now try to put it in the textarea
var d = document.createElement("INPUT");
d.setAttribute("type","button");
d.setAttribute("class","btn btn-info active pull-right");
d.setAttribute("onclick","commentThis()");
d.setAttribute("value","Add Comment");
panel.appendChild(para); // this is where a comments piece would go
// place the item
var destination = document.getElementById("journal")
//destination.insertBefore(Commentaryarea, destination.firstChild);
//destination.insertBefore(panel, destination.firstChild);
destination.insertBefore(panel, destination.firstChild);
panel.appendChild(c);
panel.appendChild(d);
document.getElementById("userInput").value = "";
document.getElementById("userInput").focus();}
</script>
<script>
function setText(a){
document.getElementById("userInput").value = a
document.getElementById("userInput").focus();
}
</script>
When you say "stored locally", do you mean stored in the visitors browser, i.e. with only themselves being able to see it and retrieve it? Or do you want other users to be able to see the data, and/or the commenter to be able to see it if they log in later from another location?
If it's the latter then you need to store it on the server side, and you're going to need a database for that. If all you need is to store journal entries then mongoDB is easy to set up with javascript, but if you have a lot of relations (journal entries being associated with users, comments on entries being associated with users and entries, ect) then perhaps an SQL database would suit you better.
Related
So this function works fine, however everytime i refresh the page the WINNER (person1 to 4) changes, i want to save the output and have it FIXED so that it wont change everytime i refresh..
Basicly: There is a timer on my website and when it hits 0 , it should automaticly pick someone from the list as the winner... but the winner should appear on the website for everyone and stay there
function randomNavn(){
document.getElementById("utskrift").innerHTML = "";
for (i = 0; i < 1; i++){
randName.push(nname.splice(Math.floor(Math.random() * nname.length), 1));
}
document.getElementById("utskrift").innerHTML = randName.join(", ");
}
var nname = ["Person1", "Person2", "Person3", "Person4"],
randName = [];
You need server-side code to do this -- and most likely a database. You can't do what you want from JavaScript. Each person's browser will run that javascript and get their own answer, bit it is only on their browser. Someone else will get a different answer, etc. That's not what you want to happen I assume.
To save data more permanently to be used in a web page, you have a few options:
Create a web service that accepts POST or PUT requests and saves the data on a server. This will allow you to share data between users.
Use a cookie. This will only save a value for each user's session. It won't share data between users.
You could use localStorage:
$window.localStorage.setItem('initData', {data: 'here'}
after some nights spent i've managed to found the perfect solution.
1) I've eliminated the javascript function for the array and instead craeted a php file where a winner or more is choosed.
2) From that php file we write the winners into a text file.
3) From that text file we read it through ajax and list it when countdown is over.
If anyone is ever in need, its good solution.
Thanks for everytning
I have a problem. i have a website am working on. I have created a php script to fetch all the receipts id from the data base using pagination, and all works fine. But the problem is every receipt id, i have added a link so as when clicked a specified results will be displayed without loading the page.
The links are like :
G145252 G785965 and when each link is clicked will show http://test.com/?go=any#G145252
When clicked the page will not reload.
So what i need help with is how can i get G145252 from the url after when the link is clicked using javascript and print it using html?
i need to pass the value to the process.php as a $GET value so the i can load the receipt detail of the clicked id with out reloading the page.
Please note: there are a lot of get values before the #value i need to get out of the url address.
You should not be using the fragment identifier section of the URI for server side related tasks. This section is intended for client-side manipulation only. More info here.
You can use some other means such as query parameters to access this data.
For example, turn this:
http://test.com/enter code here?go=any#G145252
Into this:
http://test.com?go=any&hash=G145252
Then:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
console.log(getQueryVariable("go")); // any
console.log(getQueryVariable("hash")); // G145252
NOTE: I know this is not the exact answer to your actual problem, but the question itself is presenting a bad practice scenario, thus my suggestion.
Credits for the getQueryVariable function goes to CSS Tricks: https://css-tricks.com/snippets/javascript/get-url-variables/?test=3&test2=5
Let's assume you're using jQuery.
Change all your links so that they have a common class name, lets say 'hashClick' e.g
My Link
To get the hash part when clicked, add a click event handler for those links
$('.hashClick').click( function(event) {
event.preventDefault();
var url = $(this).attr('href');
var hash = url.substring(url.indexOf('#')+1);
alert("You clicked " + hash);
// or at this point you can do an AJAX call
// or GET request to process.php with hash as one of the parameters
})
suppose this is the link
http://test.com/?go=any#G145252
to get the hash value
window.location.hash
which will return you #G145252
and
window.location.hash.substring(1) will return you "G145252"
I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.
I need to know how I can show the input data of a form after a user presses the back button.
Here is the working jsfiddle
I created a simple asp page.
If I click next after entering some input value, it will go to next page, and again I click back, it doesn't show entered input values.
$("#form").submit(function() {
var inputs=$('.input');
for(i=0;i<inputs.length;i++)validateEmail(inputs[i]);
if($('.invalid').length!==0)return false;
});
I need to show those values. How can I achieve this? Thanks in advance!
Note: In my jsfiddle didn't include next page action.
You have several methods, althought I'm not a big fan of cookies because they are not so smart to manage.
You can either use:
The localStorage API, if you want your values being saved until the user clears the cache, like this:
var myValues = [];
for(i=0;i<inputs.length;i++) {
validateEmail(inputs[i]);
myValues.push(inputs[i].value);
}
// Save them fot later use
localStorage.myValues = JSON.stringify(myValues);
// After clicking the button you can retrieve them back
var oldValues = JSON.parse(localStorage.myValues);
The sessionStorage API, which lives for the current session of the browser (i.e. when the user closes the browser it gets deleted):
var myValues = [];
for(i=0;i<inputs.length;i++) {
validateEmail(inputs[i]);
myValues.push(inputs[i].value);
}
// Save them fot later use
sessionStorage.myValues = JSON.stringify(myValues);
// After clicking the button you can retrieve them back
var oldValues = JSON.parse(sessionStorage.myValues);
NOTE: I'm using JSON.parse and JSON.stringify because both storage objects (local and session) can only store data in string format.
I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.
<script type="text/javascript">
$(document).ready(function() {
$("#fullswitch").click(function() {
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").addClass("normal");
$("#imgg").addClass("normal");
});
$("#compactswitch").click(function() {
$("#chpheader").addClass("compact");
$("#imgg").addClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
$("#originalswitch").click(function() {
$("#chpheader").addClass("original");
$("#imgg").addClass("original");
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
});
</script>
<html>
<body>
<span id="t1">0</span>
<span id="t2">0</span>
<span id="t3">0</span>
<span id="t4">0</span>
<span id="t5">0</span>
<span id="t6">0</span>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
localStorage.setItem("first", "Smi");
// Retrieve
var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>
</body>
</html>
There is a jQuery cookie plugin there are examples on that page as well so you can see how you can set and read a value from the cookie.
Once the value is read it's just a simple matter of loading the right theme.
var theme = $.cookie('name_of_selected_theme');
setTheme(theme);
function setTheme(themeName){
if(themeName == "One"){
...
}else...
}
However cookies only allow for 4KB of data and are passed in every HTTP call. A better idea many be localStorage. You can use YUI Storage Lite library which is < 3KB in size and you can easily use it to save data in browser localStorage and load from it. You can save at least 5MB of data using localStorage.
Example code from the link above:
YUI({
//Last Gallery Build of this module
gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {
// For full compatibility with IE 6-7 and Safari 3.x, you should listen for
// the storage-lite:ready event before making storage calls. If you're not
// targeting those browsers, you can safely ignore this step.
Y.StorageLite.on('storage-lite:ready', function () {
// To store an item, pass a key and a value (both strings) to setItem().
Y.StorageLite.setItem('kittens', 'fluffy and cute');
// If you set the optional third parameter to true, you can use any
// serializable object as the value and it will automatically be stored
// as a JSON string.
Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);
// To retrieve an item, pass the key to getItem().
Y.StorageLite.getItem('kittens'); // => 'fluffy and cute'
// To retrieve and automatically parse a JSON value, set the optional
// second parameter to true.
Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']
// The length() method returns a count of how many items are currently
// stored.
Y.StorageLite.length(); // => 2
// To remove a single item, pass its key to removeItem().
Y.StorageLite.removeItem('kittens');
// To remove all items in storage, call clear().
Y.StorageLite.clear();
});
});
I suppose you have two options, store the info client side, or store the info server side.
If you actually have a "user" server side (the person has to log in, yada yada yada), you can store this setting for the user (add some data to where ever the user info is stored).
If you don't want it that persistent, you can store it in local storage (not very browser friendly) or cookies. You really have no guarantee that these settings will stay around, as they are controlled by the browser, users can have their browsers set to never save this info.
Either way (client or server) you can read the setting and set the classes server-side and skip the javascript for changing the classes. Always better to do it on the server.
You may use HTML5 window.localStorage to store user preferences and trigger the corresponding layout changes.
Or use cookies as previously suggested.
Take a look at this article: http://diveintohtml5.ep.io/storage.html
Use cookies to store the users options.
http://www.quirksmode.org/js/cookies.html
Use localStorage to store the user preferences, and on reload load the preferences back in.
Here's a good tutorial.
How to write:
localStorage['someKey'] = 5;
How to read: var lastKeyValue = localStorage['someKey'];
use session storage
//set in session storage
$("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
//in that case one expanded at the time
sessionStorage.clear();
var par = $(evt.target).parent();
sessionStorage.setItem(par.attr('id'),par.attr('class'));
console.log(par.attr('class'));
});
// //retrieve class from session
if(typeof sessionStorage!='undefined') {
$('#block-menu-menu-organisation > ul > li' ).each(function(i) {
if( $(this).attr('id') in sessionStorage) {
$(this).attr('class', sessionStorage.getItem($(this).attr('id')));
}
});
}