Javascript cookies do not function - javascript

So guys, I try to make this work. When I click on a button on a page, it has to transfer the array to another page to show it. My functions addProduct, showProduct, addItem and button work. But My data from the array does not get passed to the other page. So when I click on a button in page A, a value is added to this array. But on page B it shows that the array is empty
var products = new Array();
window.addEventListener("load", loadPage, false);
window.addEventListener("load", addButton, false);
window.addEventListener("load", showProducts, false);
function addButton() {
var button = document.getElementById("sell");
button.addEventListener("click", addItem, false);
}
function loadPage(){
getCookie();
}
function getCookie(){
var elements = document.cookie.split('=');
var products_cookie = elements[1].split('%');
for(var i=0;i < products_cookie.length-1;i++) {
var tmp = products_cookie[i].split('$');
addProduct(tmp[0], tmp[1], tmp[2]);
}
}
function setCookie(){
var date = new Date();
date.setTime(date.getTime()+(2592000)); //expire time = 30 dagen nadat cookie aangemaakt is
var expires = "; expires="+date.toGMTString()
var text = "";
for (var i = 0; i < products.length; i++){
text+= products[i][0] + "$" + products[i][1] + "$" + products[i][2] +"%"; // slaat naam $ aantal $ prijs op
}
document.cookie = "tradepoint"+text+expires;
}
function addProduct(pName, pAmount, pPrice){
var product = new Array(pName, parseInt(pAmount), pPrice);
products[products.length] = product;
setCookie();
}
function addItem(){
addProduct("andrej", 2, 1);
alert(products + " " + products.length);
}
function showProducts(){
if (products.length != 0){
document.getElementById("shopList").innerHTML = "<ul><li>Full</li></ul>";
}
else{
document.getElementById("shopList").innerHTML = "<ul><li>Empty</li></ul>";
}
}

Cookies are represented as name=value pairs, your setCookie function doesn't do that you should have document.cookie = "tradepoint="+text+expires; notice the = sign.
Also your getCookie function may not work if there are other cookies being set.

Are you testing this against localhost? Cookies will not "stick" to TLDs. You need at least x.y.z - use an alias to 127.0.0.1 in your hosts file to test cookie related code.
(stackoverflow won't let me post an url to localhost - anti-trolling technology I presume!)

Related

How to exchange counter after delete field using plain javascript

I'm new in javascript. i have a JS function that add and remove input fields. its working fine with my JS function. But I want when delete a field its Id looks like:
I have
no. 1
no. 2
no. 3
After Delete 2:
no. 1
no. 2
already i got this answer:
Reset JavaScript Counter after Deleting a field
But i want it with plain javascript. Can anyone help?
<script>
var count = 1;
function add_new(){
count++;
var div1 = document.createElement('div');
div1.id = count;
var delLink = '<button type="button" onclick="deleteLink('+count+')" class="btn btn-primary">Delete</button>';
div1.innerHTML = document.getElementById('add_link1').innerHTML+delLink;
document.getElementById('add_link').appendChild(div1);
document.getElementById("input_link1").id = count;
document.getElementById("input_link2").id = count;
document.getElementById("input_link3").id = count;
}
function deleteLink(eleId){
var ele = document.getElementById(eleId);
var par = document.getElementById('add_link');
par.removeChild(ele);
}
</script>
After deleting an element call the following function to reset Id of existing elements and also reduce the count.
function reset_counter(deletedCount) {
for (var impactedElementId = deletedCount + 1; impactedElementId < count; impactedElementId++) {
var currentElement = document.getElementById(impactedElementId);
currentElement.id = impactedElementId - 1;
var button = currentElement.firstChild;
button.innerHTML = 'Delete ' + currentElement.id;
button.setAttribute('onclick', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
The full code is available here: AddDeleteElements Sample Code

Cant call Jquery function in if loop

my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}
I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });
Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did

The results are not displaying on the screen but im getting no console error

I am using the following code to run a query against the database that returns the information I want. I now want to display it on the screen.
function display(parsed) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < parsed.length; i++) {
var item = parsed[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
};
article.innerHTML = item;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
However this does not display the results on the screen. I used console.log to see if it was the getItems function that was not working but this logs the information I want so I am getting the correct information I just need it to display on the screen but i don't know why it is not?
below is what is logged in the console.
{"rows":[{"P_ID":"1","P_NAME":"Iphone 6","P_DESCRIPTION":"the latest iphone","P_PRICE":"300"},{"P_ID":"2","P_NAME":"Ipad Mini","P_DESCRIPTION":"the latest and smallest ipad","P_PRICE":"199.99"},{"P_ID":"3","P_NAME":"MacBook Pro","P_DESCRIPTION":"the macbook pro","P_PRICE":"999"},{"P_ID":"4","P_NAME":"Ipad Cover","P_DESCRIPTION":"a cover for ipad","P_PRICE":"30"},{"P_ID":"8","P_NAME":"Iphone 5c","P_DESCRIPTION":"the iphone 5c","P_PRICE":"150"},{"P_ID":"9","P_NAME":"Windows 8 laptop","P_DESCRIPTION":"a laptop with windows 8","P_PRICE":"250"}]}
It looks like you're passing the raw response text to your function instead of the parsed object.
Should be this:
xhr.onload = function() {
console.log(this.response)
var parsed = JSON.parse(this.responseText);
display(parsed); // <-----
};
There are also several issues in your display function:
// v----- this said parsed instead of results
function display(results) {
article = document.getElementById("homeArticle");
item = '<p>Something should go here</p>';
for (var i = 0; i < results.length; i++) {
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
// next I add to the string that we want to place on the page
item += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
}
article.innerHTML = item; // needs to be innerHTML
}
Edit: Your array is on a property called rows, so you either need to access this property when passing it into display():
display(parsed.rows);
Or access it inside your display() function:
function display(response) {
var results = response.rows;
...
}

How do I get this code to work on google sites?

I have this code:
var links = [cant put links in yet] var visited = [];
var button = document.getElementById('btn');
button.addEventListener('click', function() {
if (visited.length == links.length) {
alert('You visited all the links');
return;
}
var random, url;
do {
random = Math.floor(Math.random() * 4);
url = links[random];
} while (contains(visited, url));
alert('Opening: ' + url + ' with #' + random);
visited.push(url);
var win = window.open(url, '_blank');
win.focus(); });
function contains(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
and I need to combine it together and put it on to a google site. I tried combing it all with tags in an html box, but all that does is create my button. It doesn't run the script and open the links... Will this code not work on google sites or am I doing it wrong?
FULL CODE w/html and css
On the Html Box , you can't.
You can use this code with App Engine or use Google App SCript.
you can see an example here : http://tutorialzine.com/2011/01/google-appengine-series/

Check a value from Array in javascript?

I have a:
var pageURL = location.href; // stores the URL of the current page in the var pageURL
And I have :
var Page = Array ();
page [0] = "http://web1.com"
page [1] = "http://web2.com"
page [2] = "http://web3.com"
Now I want to make a function (called nextPage) to check which one of these pages in the array equals the PageURL. Also I need to have a button, so when I click it it will take me to the next page. What that mean I want to increment the page by 1.
You can use very simply
var current = page.indexOf(location.href);
Then to go to the next page
location.href = page[current + 1];
var form = document.createElement('form');
form.id = "nextForm";
document.body.appendChild(form);
var nextButton = document.createElement('input');
nextButton.type = 'button';
nextButton.id = 'nextButton';
nextButton.value = 'Next Button';
nextButton.onclick = nextPage;
form.appendChild(nextButton);
function nextPage() {
var page = Array ();
page[0] = "http://web1.com" // insert your urls here
page[1] = "http://web2.com"
page[2] = "http://web3.com"
var matchIndex = page.indexOf(location.href);
var nextIndex;
if (matchIndex !== -1 && page[matchIndex + 1]) {
nextIndex = matchIndex + 1;
} else {
alert("You're at the last page"); // next page in the array does not exist, you can handle the error however you want
return;
}
goToNextPage(page[nextIndex]);
}
function goToNextPage(url) {
document.location.href=url;
}
Based on Joseph's answer the full code would look something like this:
function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}
Also if support for indexOf is an issue for you in IE check out the answer to that from another StackOverflow question: How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Categories

Resources