It only shows the latest data? - javascript

In that case, I put 1 2 3 in each input and it only shows number 3. How can I fix it? I'm sorry if it's a stupid question but I really don't know.
function WriteCookie()
{
cookievalue= document.myform.firstname.value+";";
cookievalue1= document.myform.memory.value+";";
cookievalue2= document.myform.half.value+";";
cookievalue3= document.myform.lose.value+";";
document.cookie=cookievalue;
document.cookie=cookievalue1;
document.cookie=cookievalue2;
document.cookie=cookievalue3;
alert(document.cookie);
}

You rewrote document.cookie 4 times with a new value each time.
If you'd like to combine data from all 4 vars uses code like:
function WriteCookie()
{
var cookievalue = document.myform.firstname.value+";";
var cookievalue1 = document.myform.memory.value+";";
var cookievalue2 = document.myform.half.value+";";
var cookievalue3 = document.myform.lose.value+";";
cookievalue = cookievalue + cookievalue1 + cookievalue2 + cookievalue3;
document.cookie = cookievalue;
alert(document.cookie);
}

Related

What is the significance of the if statement in this code?

I am currently learning JavaScript through some tutorials and this example came out in the tutorial.
I'm just confused why must the if statement be there.
I tried erasing the if statement and it still worked. Can someone help me please.
var timesVisited=0;
var dateVisited = 'Never';
if(localStorage.myLastVisit){
var visit = JSON.parse(localStorage.myLastVisit);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
}
$("#dateVisit").html(dateVisited);
timesVisited++;
$("#numVisit").html(timesVisited);
var myVisits = {};
myVisits.numVisits = timesVisited;
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
myVisits.dateVisits = hours + ':' + minutes;
localStorage.myLastVisit = JSON.stringify(myVisits)
I tried erasing the if statement and it still worked.
Only if myLastVisit is already in localStorage. If it isn't there (which is what the if is testing for), without the if you'll get an error from JSON.parse because you'll pass undefined into it, which will get converted to a string with the charactersundefined in it because JSON.parse requires a string, which will then fail because that's not valid JSON. The if is there so that if the setting isn't present, the default values assigned to timesVisited and dateVisited are used.
Works if the setting is there:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(`{"numVisits": 2, "dateVisits": "2020-03-27"}`);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited); // 2
console.log(dateVisited); // "2020-03-27"
Fails if it isn't:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(undefined); // ERROR
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited);
console.log(dateVisited);

Looking to read cookie array in Console

Written this piece of Code to pass array into Cookie
<script>
var products = [];
{
var products = [{
'name': '$1 Silver Membership Trial - Silver-Membership-3-Month',
'price': '279.88',
'quantity': 1
}]
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
createCookie('products', JSON.stringify(products));
createCookie('revenue', 279.88);
</script>
When trying to this piece Code in Console does not get array value
console.log(JSON.stringify(createCookie.get('products')));
To get all cookies for the current domain you can use document.cookie.
If you want to get a specific cookie, you must work with that string and extract it.
You can use this function to get a cookie buy it's name:
function getCookieByName(cookiename) {
const cookieString = RegExp(cookiename + "=[^;]+").exec(document.cookie);
return decodeURIComponent(!!cookieString ? cookieString.toString().replace(/^[^=]+./, '') : '');
}
and then just call it like this:
console.log(getCookieByName('products'));

How do I use Jquery variable variables? [duplicate]

This question already has answers here:
Access Javascript variables dynamically
(4 answers)
Closed 8 years ago.
I know there are a lot of questions about if it is possible to use variable variables in jQuery.
One of the questions is this one: click here.
I tried to use the answer, but I don't know how I can use it in my case.
var numberofquestions = 10;
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
/* ------ first part ------- */
if (i==1) {
dataString = dataString + "q1=" + question1 + "&";
} /* ------ end first part ------- */
else if (i == numberofquestions) {
questionValue = "question" + numberofquestions;
qValue = "q" + numberofquestions;
dataString = dataString + qValue + "=" + questionValue;
console.log(dataString);
} else {
questionValue = question + i;
dataString = dataString + "q" + i + "=" + questionValue + "&";
}
}
The loop will run 10 times, and each time it needs to add a part to the already existing dataString.
What it needs to do is make this string:
q1=(value of var question1)&q2=(value of var question2) and so forth.
The vars question1, question2, ... question10 all hold a number.
The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:
q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10
Does anybody know what I'm doing wrong?
You should use an array for this. There is no such thing as "variable variables" in JavaScript.
You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.
In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.
I'm not sure why you're using "question" + numberofquestions which will be 10 every time

Run function after each() jQuery

I know that the each() in jQuery is synchronous, but it doesn't seem to behaving that way. When I do this:
$('#findRankBtn').click(function () {
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
var pageNumber = $('#currentPage').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
searchGoogle(searchTerms, pageNumber, websiteURL);
});
function searchGoogle(searchTerms, pageNumber, websiteURL) {
$.getJSON("https://www.googleapis.com/customsearch/v1?key=AIzaSyDPuIrijE0IQ6330vMLN2p-L_4J6y_G60c&cx=013036536707430787589:_pqjad5hr1a&q=" + searchTerms + "&alt=json&start=" + pageNumber,
function (recievedData) {
//console.log(recievedData);
$.each(recievedData.items, function (i, item) {
$('#resultsDiv').append('<p class="resultLink">' + item.link + '</p>');
var linkAddress = $('.resultLink:last').text();
if (linkAddress.indexOf(websiteURL) !== -1) {
alert('found');
$('.resultLink:last').attr('class', 'yourLink');
$('#ifFound').attr('value', 'true');
}
});
var ifFound = $('#ifFound').val();
var currentPage = $('#currentPage').val();
var nextPage = CurrentPage + 1;
if (ifFound == 'false') {
//INCREMENT PAGE
$('#currentPage').attr('value', nextPage);
//GRAB DATA AGAIN
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
//SEARCH GOOGLE
searchGoogle(searchTerms, nextPage);
}
});
}
Basically if it doesn't find the desired link on the first page of results, it should go on to the next page. I have a working fiddle for just the first page here: http://jsfiddle.net/p8DY3/1/
so how can I get searchGoogle() to run until it finds what it's looking for?
Maybe there's a better way of going about it that's in the Google API that I don't know about?
Sorry if my question is amateur, I've only begun to learn JavaScript on my own a month ago.
First you should make sure you are not hitting some sort of rate limit from Google. Look at your Network tab to see if the requests are coming back correctly.
First issue I see is bad math.
var currentPage = $('#currentPage').val(); is a string
Here var nextPage = CurrentPage + 1; you are treating it as a number.
You got to convert the string to a number before you add to it. You are doing string concatenation!.
var nextPage = parseInt(CurrentPage,10) + 1;
NITPICKS
Do not store things in inputs. Use variables, it will make things go so much faster. DOM lookup/manipulation is slow.
Why are you reinventing addClass and val()
$('.resultLink:last').attr('class', 'yourLink');
$('#currentPage').attr('value', nextPage);
should be
$('.resultLink:last').addClass('yourLink');
$('#currentPage').val(nextPage);
Why are you grabbing the search terms and website url again? You already have them passed into the function?
Finally your problem
searchGoogle(searchTerms, nextPage); <-- What are you missing here?
function searchGoogle(searchTerms, pageNumber, websiteURL) { <--what it is expecting
You are passing in 2 things when it wants 3.

How to handle cookies in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the “best” way to get and set a single cookie value using JavaScript
I am working on a project where it requires to check cookie and tell whether it is 20 minutes old or not. So I have written once code which is like this.
This is only javascript code I have pasted.
function checkcookie()
{
var difftime= getcookie();
// further operation comes here
}
var cookieminutes;
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
if(start==-1)
{
cookiedate = new Date();
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
cookieminutes= cookiedate.getMinutes();
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}
In function getcookie the variable cookieminutes is coming as undefined. But as I know since it is a global variable it should have the value.
Can anybody please tell what is the solution for this.?
You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.
Try this:
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
cookiedate = new Date();
cookieminutes = cookiedate.getMinutes();
if(start==-1)
{
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}
If you want to use global variables (generally bad design) set and access them explicitly with window. E.g.:
window.cookieminutes = cookiedate.getMinutes();
and later:
document.write("Cookie minutes is "+window.cookieminutes);
And drop the var cookieminutes;
As I said in my comment, it looks like if getcookie is being called for the first time on a given page load, and the cookie exists (start != -1), cookieminutes is never set. You need to make sure you don't use undefined variables.

Categories