Simple shopping cart using JavaScript Cookie - javascript

I have following code to implement simple practice shopping cart using JavaScript. There is a checkout link which calls getcookie() to check the value of the cookies stored. When nothing is in the cookie then click on the link alerts to make input. If non of the values are entered in the input box and hit "add to cart" then validation is done and error message is alerted.
For some reason, the cookie is not taking the value from the input field. I tried quite a while now but was not able to debug the code. Just an empty alert box is shown at last. I appreciate any debugging. Thanks in advance.
<script type="text/javascript">
var value;
var productID;
function setItem(abd) {
value = abd.value;
productID = abd.getAttribute("productID");
var intRegex = /^\d+$/;
var numberOfItems;
if (!intRegex.test(value) || (value <= 0)) {
alert('Please Enter valid numberofitem');
} else {
numberOfItems = value;
}
}
function getCookie() {
if (value == undefined) {
alert("There is nothing in the shopping cart!");
} else {
var cookieArray = document.cookie.split(';');
var printHolder = "";
for (var i = 0; i < cookieArray.length; ++i) {
var pairArray = cookieArray[i].split('=');
alert(pairArray[0]);
}
alert(printHolder);
}
}
function setCookie() {
if (value == undefined) {
alert("Please add number of items in text box");
} else {
document.cookie = productID + "=" + value + "; ";
alert(value + " Product(s) with id " + productID +
" has been added to shopping cart!");
}
}
</script>
Checkout
<input name="item-select" id="item-select"
productid="p001" style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>
The result I wanted is something like this at last!

This code works perfectly fine with some changes.
I was using chrome and later found out that
Google Chrome doesn't create cookies when the file is on the local machine and loaded in browser directly using file path.
Rather try with localhost. It is definitely working when you put the code in server. Chrome became pain in a b*t here!
If you were for idea on creating shopping cart with Javascript follow this link.
http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/

Your getCookie is likely to give you incorrect results.
var cookiearray= document.cookie.split(';');
var toprint="";
for(var i=0; i<cookiearray.length; ++i)
{
var pairArray= cookiearray[i].split('=');
alert(pairArray[0]);
}
alert(toprint);
Two things wrong here;
1) When you are in your for loop, each time you loop you are alerting the first item in your array at all times pairArray[0] you need to change that to pairArray[i]
2) You are displayed with an empty alert because thats what you have assigned to the toprint variable.
- You assign toprint an empty string before your for loop, then you are alerting that variable without assigning it a new value, so you will be displayed with an empty alert box!
- Also make sure your cookie array is not empty.
Give that a try, enjoy coding :)
Kush

Related

$.getJSON returns undefined then returns requested data

I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.
Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!
$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
event.preventDefault();
var input = {search: $(this).val()};
getWikiInfo(input);
}
});//search end
function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
console.log(response);
var wikipHtml;
for(var i = 1; i < 6; i++) {
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
$("#list-container").html(wikipHtml);
}
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end
You need to do minor change. Initialize wikipHtml to empty string and check if the response[1][i] is not undefined. Below is the updated code:
var wikipHtml = '';
for (var i = 1; i < 6; i++) {
if (response[1][i] !== undefined)
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
This is happening because you are not initializing wikipHtml before appending to it, but I would strongly advise that you use proper DOM manipulation instead of building your HTML using string concatenation:
$("#search-word").on("keydown", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var input = {
search: $(this).val()
};
getWikiInfo(input);
}
}); //search end
function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
var content = [0, 1, 2, 3, 4, 5].map(function(i) {
return $('<div class="list">')
.append($('<h3>').text(response[1][i]))
.append($('<p>').text(response[2][i]));
});
$("#list-container").html(content);
}
$.getJSON(wikipApi, input, getWikipHtml);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-word' type='text' />
<div id='list-container'></div>

scope access in angular js

I am having trouble accessing a variable using angularjs and ionic. I have a page where I am listing an amount of items:
<ion-item ng-repeat="item in items"
item="item"
href=""
style="max-height:70px; padding: 0px 0px 0px 0px;"
>
<div class="containerText" style="position:absolute; float:left; margin-left:60px">
<div class="" style="font-size:11px">
{{item.datea}}
</div>
<div class="" style="margin-top:4px; font-weight:bold; text-align:right">
{{item.value}}
</div>
</div>
(...)
And I want to load the item.value when I press the "download" button that each item row has next to the delete icon:
I am converting all the numbers to strings in the input field to make it easier to control the changes (like adding a decimal point or deleting the last value of that string).
My controller.js has these functions:
$scope.searchText = "0";
(...)
/****************** KEYBOARD FUNCTIONS ************************/
//Adds a number in the field text above the keyboard
$scope.addNumber = function(num) {
//limiting the amount of numbers in the display
if (this.searchText.length < 20)
if (this.searchText == "0")
if (num != '.')
this.searchText=num;
else
this.searchText = (this.searchText) + num;
else
if (num!='.')
this.searchText = (this.searchText) + num;
else if (this.searchText.indexOf('.') == -1)
this.searchText = (this.searchText) + num;
}
//Used to delete the number in the screen and set it to 0
//AKA RESET
$scope.deleteNumbers = function(){
this.searchText= "0";
console.log("ERASING!");
}
//Used to delete the last entered digit/symbol
$scope.deleteLast = function(){
this.searchText = this.searchText.slice(0, -1);
if (this.searchText.length==0)
{
this.searchText = "0";
}
}
//used to load the values of an element of the list to the display
$scope.loadItem = function(valueToAdd){
console.log("Load values ");
$scope.deleteNumbers();
$tempVal = valueToAdd.toString();
$scope.addNumber($tempVal);
console.log("value in this.searchText " + this.searchText);
console.log("value in scope.searchText " + $scope.searchText);
console.log(isNaN($tempVal));
}
And it loads nicely the first execution (only if I have not pressed the coded keyboard before), but after touching my created keyboard, the "load number" function stops working.
My console.log looks like this when I load the page and I press one of thos download buttons:
controllers.js:185 Load values
controllers.js:77 ERASING!
controllers.js:212 value in this.searchText 14458.553
controllers.js:213 value in scope.searchText 14458.553
controllers.js:214 false
As you can see, it says that it is a numeric value that has been loaded into the field, but it let's me add additional numbers or delete the chars of the input string without problem, but if I want to load another value (or even the same previously loaded) it seems that the scope gets messed up as I get this output.
controllers.js:185 Load values
controllers.js:77 ERASING!
controllers.js:212 value in this.searchText 14458.55
controllers.js:213 value in scope.searchText 15429.477
controllers.js:214 false
I have tried modifying at the same time this.searchText and scope.searchText but without result. What can I do to fix this?

How do I write javascript cookies from a form and then print the info in an alert or hidden div?

How do I use JavaScript to write cookies from form fields, and then print the info in an alert or hidden div?
Here is an example of what I have tried thus far.....
<script type="text/javascript">
function cookieForm() {
document.cookie = "name_first" + encodeURIComponent(document.forms[0].name_first.value);
}
function printCustomerInfo() {
var queryData = decodeURIComponent(document.cookie);
var queryArray = queryData.split(";");
if (document.cookie) {
window.alert("Your info. is:" + queryArray[0]);
window.alert[0].name_last.value = QueryArray[1].substring(queryArray[1].lastIndexOf("=") + 1);
}
}
</script>
<input type="submit" value="Submit" onclick="cookieForm(), printCustomerInfo()"/>
First, you're missing the "=" in the cookie string:
document.cookie = "name_first=" + encodeURIComponent(document.forms[0].name_first.value);
Second, your queryData has no ";" to split by, and no last name value - at least from what you show here.
This I do not understand:
window.alert[0].name_last.value = ...
I would call a single function from your event, and let that parent both setting the cookie and parsing it. That way you can at least debug it better.
re: a div, you could do something like this:
document.getElementById("yourDiv").innerHTML = "Your info. is:" + queryArray[0];
document.getElementById("yourDiv").style.visibility = 'visible';
But in general it's better to use jquery for manipulating elements, because it mitigates browser differences, though it wouldn't matter in this case:
$("yourDiv").html("Your info. is:" + queryArray[0]);
$("yourDiv").css ( { 'visibility': 'visible' } );
Good luck.

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

validating checkbox ticked with javascript

Ive got some javascript im using to validate a form which works fine but I now need to add a checkbox which needs to be checked before the form submits. The name of the checkbox is terms in the html and ive managed to get it to not submit the form using the code below.
$(document).ready(function(){
$("#sendmail").click(function(){
var valid = '';
var isr = ' is required.';
var name = $("#name").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var country = $("#country").val();
if( !$("#terms").is(":checked") ){
valid += '<br />Please accept the terms and conditions.';
}
if (name.length<1) {
valid += '<br />Name'+isr;
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<br />A valid Email'+isr;
}
if (subject.length<1) {
valid += '<br />Website Link'+isr;
}
if (country.length<1) {
valid += '<br />Country'+isr;
}
if (valid!='') {
$("#response").fadeIn("slow");
$("#response").html("Error:"+valid);
setTimeout('$("#response").fadeOut("slow")',4000);
}
else {
var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&country=' + country;
$("#response").css("display", "block");
$("#response").html("<img src='http://infashionation.com/female/images/response.jpg'>");
$("#response").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
The problem is it now doesnt submit regardless of whether box is checked or not.
Ive been searched for some information to help me with this for a while but no luck so thought I would ask here to see if anyone can help me.
There appears to be an extra exclamation point after the valid variable. I suggest also using a javascript debugger.
if (valid!='') {
You're missing a closing curly brace for your .ready function.
It doesn't look like you've closed the $(document).ready() function. You close the sendmail click function, but not the main function. I think the tail end of your code should look like this:
}
return false;
}); // close sendmail function
}); // close document.ready
If that happened because of copying it to SO, then disregard this, but if this is in your code, your browser will probably not do a thing and appear not to react to the JavaScript.

Categories

Resources