How to fix undefined variables after program runs - javascript

The program will ask for all inputs and print everything but the variables all come up as undefined.
This is for a web application tied to a HTML document. No errors are thrown when it runs.
function driver(){
var plan1Code = "S";
var plan1Cost = 450;
var plan1Hours = 2.5;
var plan1Pics = 75;
var plan2Code = "G";
var plan2Cost = 750;
var plan2Hours = 5;
var plan2Pics = 125;
var plan3Code = "P";
var plan3Cost = 1000;
var plan3Hours = 8;
var plan3Pics = 225;
var retName = getName();
var retPlan = getPlan();
var retHours = getHours();
var retPics = getPics();
var baseCost, totalCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost;
if (retPlan == plan1Code){
baseCost = plan1Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan1Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan1Pics);
}
else if (retPlan == plan2Code){
baseCost = plan2Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan2Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan2Pics);
}
else if (retPlan == plan3Code){
baseCost = plan3Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan3Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan3Pics);
}
totalCost = calcTotalCost(baseCost, upchargeTimeCost, upchargePicsCost);
print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost);
}
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
}
function calcTimeUpcharge(hours, baseHours){
upchargeTime = hours - baseHours;
var price;
if (upchargeTime>0){
var upchargeTimeUnits = Math.ceil((upchargeTime)/.5);
upchargeTimeCost = upchargeTimeUnits * 50;
}
else {
upchargeTime = 0;
upchargeTimeCost = 0;
}
return upchargeTime, upchargeTimeCost;
}
function calcPicsUpcharge(pics, basePics){
upchargePics = pics - basePics;
if (upchargePics>0){
upchargePicsunits = Math.ceil((upchargePics)/10);
upchargePicsCost = upchargePicsunits*40;
}
else {
upchargePics = 0;
upchargePicsunits = 0;
}
return upchargePics, upchargePicsCost;
}
function calcTotalCost(baseCost, timeCost, picsCost){
return baseCost + timeCost + picsCost;
}
function print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost){
document.write(retName + ", thanks for using Photosarus!" + "\n");
document.write("<br><br>");
document.write("You selected plan " + retPlan + " at a cost of "+ baseCost );
document.write("<br><br>");
document.write(upchargeTime + "additional hours at a cost of "+ upchargeTimeCost);
document.write("<br><br>");
document.write(upchargePics + "additional pictures at a cost of "+ upchargePicsCost);
}
I expect the output to say
Bill, thanks for using Photosarus!
You selected plan S at a cost of $450
0 additional hours at a cost of $0
0 additional pictures at a cost of $0
But instead I get
undefined, thanks for using Photosarus!
You selected plan undefined at a cost of undefined
undefined additional hours at a cost of undefined
undefined additional pictures at a cost of undefined

You need to return the values from the functions:
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
return name;
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
return plan;
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
return hours;
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
return pics;
}

Related

Add Campaign Selector in Adwords Script

I have a bid-to-position script that targets keywords that have a label associated with them. The label contains the desired position and the script adjusts the keyword's bid in order to reach that position. Right now the script targets any keyword with the label. I'm trying to edit the script so it will look for labeled keywords in campaigns that I choose. I tried adding .withCondition(CampaignName = ' My Campaign Name'") to the labelIterator variable but had no luck. Can anyone point me in the right direction?
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.2
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 5.00;
// Bids will not be increased past this maximum.
var minBid = 0.10;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 1.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = false;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.2;
var bidDecreaseProportion = 0.4;
var targetPositionTolerance = 0.2;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
var labels = row["Labels"].toLowerCase().split("; ")
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
try {
updateKeywords();
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var content = resultsString();
file.setContent(content);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords() {
var keywordIterator = AdWordsApp.keywords()
.withIds(uniqueIds.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
so CampaignName isn't a valid with condition for the label selector. What you need to do instead is have a Campaign Selector in a while look before you come to your Label selector, which then feeds from the campaign iteration. I've done a quick and dirty example below, but of course, you'd have to take a look to see if doing this will require other changes later on (or earlier on) in your code.
var labelIds = [];
var campaignIterator = AdWordsApp.campaigns()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.get()
while (campaignIterator.hasNext())
{
var campaign = campaignIterator.next()
var labelIterator = campaign.labels()
.withCondition("CampaignName CONTAINS_IGNORE_CASE 'MY CAMPAIGN NAME' ")
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
}
var labelIterator = AdWordsApp.labels()

Multiplying variables and showing result in a box

I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
});

Gender showed null on webpage but I wanted it to display either male or female

I want to display gender -- male or female on web page not null.
function validate() {
var fieldsValid = true;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var zip = document.getElementById("zip").value;
var gender = document.getElementById("gender");
var prevcourse = document.getElementById("course");
if(city.length == 0) {
fieldsValid = false;
if(!document.getElementById("cityErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "cityErrMsg";
errMsg.appendChild(document.createTextNode("*City is required"));
document.getElementById("cityId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("cityErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
}
}
if(state == "select one") {
fieldsValid = false;
if(!document.getElementById("stateErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "stateErrMsg";
errMsg.appendChild(document.createTextNode("*State is required"));
document.getElementById("stateId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("stateErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
}
}
if(zip.length == 0) {
fieldsValid = false;
if(!document.getElementById("zipErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "zipErrMsg";
errMsg.appendChild(document.createTextNode("*Zip is required"));
document.getElementById("zipId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("zipErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
}
}
if(document.querySelector('input[name = "gender"]:checked') == null){
fieldsValid = false;
if(!document.getElementById("genderErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "genderErrMsg";
errMsg.appendChild(document.createTextNode("*Gender is required"));
document.getElementById("genderId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("genderErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
gender = document.querySelector('input[name = "gender"]:checked').value
//this place im not sure if i have to add code to display male or female on a webpage
}
}
if(document.querySelector('input[name = "course"]:checked') == null) {
fieldsValid = false;
if(!document.getElementById("prevErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "prevErrMsg";
errMsg.appendChild(document.createTextNode("*Previous course is required"));
document.getElementById("prevcourseId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("prevErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
}
addPreviousCourses();
}
if(document.getElementById("inputDiv")) {
document.getElementById("inputDiv").remove();
}
function addPreviousCourses() {
outputCourses = "";
iArray = [];
if(document.getElementById("asp").checked) {
iArray.push (document.getElementById("asp").value);
}
if(document.getElementById("java").checked) {
iArray.push (document.getElementById("java").value);
}
if(document.getElementById("php").checked) {
iArray.push (document.getElementById("php").value);
}
for (var i = 0; i < iArray.length; i++) {
if(i < iArray.length - 1) {
outputCourses += iArray[i] += ", ";
}
else {
outputCourses += iArray[i];
}
}
}
if (fieldsValid){
var display = document.createElement("div");
var city = document.createTextNode("City: " + city);
var state = document.createTextNode("State: " + state);
var zip = document.createTextNode("Zip: " + zip);
var gender = document.createTextNode("Gender: " + gender);
var prevcourse = document.createTextNode("Previous course: " + outputCourses);
display.appendChild(city);
display.appendChild(document.createElement("br"));
display.appendChild(state);
display.appendChild(document.createElement("br"));
display.appendChild(zip);
display.appendChild(document.createElement("br"));
display.appendChild(gender);
display.appendChild(document.createElement("br"));
display.appendChild(prevcourse);
display.id = "inputDiv";
document.body.appendChild(display);
}
}
Without seeing your HTML code, this is more of a guess than anything, but I think I can tell where the issue is... and I'd say that there are actually two issues with it:
It seems that you have two radio buttons with name gender, but at the top of your code you are reading the value of the element with id gender:
var gender = document.getElementById("gender");
if there is no element with id gender, then the variable gender will have the value null, that is what you display.
Now you may say "Ok, even if I made that mistake, I shouldn't get null as I am still updating the value of the gender variable in this section":
if(document.querySelector('input[name = "gender"]:checked') == null){
fieldsValid = false;
if(!document.getElementById("genderErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "genderErrMsg";
errMsg.appendChild(document.createTextNode("*Gender is required"));
document.getElementById("genderId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("genderErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
gender = document.querySelector('input[name = "gender"]:checked').value
//this place im not sure if i have to add code to display male or female on a webpage
}
}
But... are you really? The answer is "no". Let's analyze the code (in pseudo-code):
If there isn't any gender radio button checked
Create and show an error message
Else (there is a gender radio button checked)
If there is an error message:
Hide the error message
Update the value of the gender variable
As you can see, even if you had one element with id gender and the variable was initialized to a valid value different from null, you are never updating the value of the gender variable to the value of the checked gender radio button unless you made a mistake first!.
The solution is easy: move the update from inside the if to outside the if (step 2.1.2 to step 2.2). The code would look like this:
if(document.querySelector('input[name = "gender"]:checked') == null){
fieldsValid = false;
if(!document.getElementById("genderErrMsg")) {
var errMsg = document.createElement("span");
errMsg.id = "genderErrMsg";
errMsg.appendChild(document.createTextNode("*Gender is required"));
document.getElementById("genderId").appendChild(errMsg);
}
}
else {
var toRemove = document.getElementById("genderErrMsg");;
if(toRemove){
toRemove.parentNode.removeChild(toRemove);
}
gender = document.querySelector('input[name = "gender"]:checked').value
}
And if I'm correct (and again, this is a bit of a guess) that should solve your issue.

Javascript Functions, Uncaught syntax error, Unexpected token?

The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}

changing element ID to data-code?

instead of using the ID element, data-code. Do I just change everything that is .getElementById to getElementByData-code ?
// form validation function //
function validate(form) {
var s_name = form.s_name.value;
var s_email = form.s_email.value;
var s_drop = form.s_drop.value;
// var s_promo = form.s_promo.value;
var nameRegex = /^[A-Za-z\d_]+$/;
var emailRegex = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/;
var msgRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
if(s_name == "") {
inlineMsg('s_name','You must enter your name.',2);
return false;
}
if(!s_name.match(nameRegex)) {
inlineMsg('s_txt','You have entered an invalid name.',2);
return false;
}
if(s_email == "") {
inlineMsg('s_email','<strong>Error</strong><br />You must enter your email.',2);
return false;
}
if(!s_email.match(emailRegex)) {
inlineMsg('s_email','<strong>Error</strong><br />You have entered an invalid email.',2);
return false;
}
if(s_drop == "") {
inlineMsg('s_drop','<strong>Error</strong><br />You must select your gender.',2);
return false;
}
/*
if(s_promo == "") {
inlineMsg('s_promo','You must enter a message.');
return false;
}
*/
if(s_promo.match(msgRegex)) {
inlineMsg('s_promo','You have entered an invalid message.',2);
return false;
}
return true;
}
// START OF MESSAGE SCRIPT //
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
var msg;
var msgcontent;
if(!document.getElementById('msg')) {
msg = document.createElement('div');
msg.id = 'msg';
msgcontent = document.createElement('div');
msgcontent.id = 'msgcontent';
document.body.appendChild(msg);
msg.appendChild(msgcontent);
msg.style.filter = 'alpha(opacity=0)';
msg.style.opacity = 0;
msg.alpha = 0;
} else {
msg = document.getElementById('msg');
msgcontent = document.getElementById('msgcontent');
}
msgcontent.innerHTML = string;
msg.style.display = 'block';
var msgheight = msg.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
msg.style.top = topposition + 'px';
msg.style.left = leftposition + 'px';
clearInterval(msg.timer);
msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
if(!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
}
// hide the form alert //
function hideMsg(msg) {
var msg = document.getElementById('msg');
if(!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
}
// face the message box //
function fadeMsg(flag) {
if(flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if(flag == 1) {
value = msg.alpha + MSGSPEED;
} else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if(value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
} else if(value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
}
Since you are using jQuery, you can use the Sizzle Selection Engine (packaged with jQuery) to select the elements you want by attribute:
//this will select all elements with the `data-code` attribute with a value of `whatever`
var data_codes = $('[data-code="whatever"]');
You can also just select all elements with a certain attribute regardless of the value of that attribute:
var data_codes = $('[data-code]');
Here's a list of selector types that jQuery has (at the top of the list are the attribute selectors): http://api.jquery.com/category/selectors/
Note that document.getElementById('SOME_ID') is the same as $('#some_id')[0]. I added the [0] to the end of the jQuery selection to return just the DOM node. You are using other functions that jQuery makes easier as well. .innerHTML = 'some string'; is the same as .html('some string');, .style.display = 'block' is the same as .show() or .css({display: 'block'}).

Categories

Resources