add javascript variable to click to call link - javascript

What I am trying to do is add a javascript variable to a click to call href so that whenever the phone number changes from the javascript the click to call href will change as well. The javascript that defines the variable has a default value (ex: 1-800-555-1212), but can change whenever the page loads where the tfid defines a different phone number (ex: http://www.domain.com?tfid=8663337777)
Here's an example of what's there currently:
<a href="tel:<this phone number needs to be dynamic as well>">Call this number: <script language="javascript" >
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if(tn!="")
{
setcookie(key,tn);
}
getcookie();
</script></a>
EDIT:
In order to show all elements to how the phone number is shown or switched out, I've included the javascript below that is called whenever a page loads:
// JavaScript Document start
//function to set cookie from the URL
function pixelfire(debug)
{
var phone_number=getVar("phone_number");
var keyword=getVar("keyword");
var source=getVar("source");
if(keyword)
{
//document.write("set phone number "+phone_number);
//document.write("set keyword "+keyword);
setcookie(keyword,phone_number);
//document.write("back from set cookie");
}
else
{
var keyword=get_named_cookie("MM_Keyword");
var phone_number=get_named_cookie("MM_TrackableNumber");
//document.write("retrieved keyword "+keyword);
//document.write("retrieved phone number "+phone_number);
if(keyword)
{
}
else
{
return null;
}
}
if(debug)
{
document.write("here are cookies<BR><P>"+document.cookie);
}
var campaign=getVar("campaign");
var content=getVar("content");
//document.write("location is "+location);
var url="http://www.mongoosemetrics.com/pixelfire.php?phone_number="+phone_number;
var url = url + "&keyword="+keyword;
var url = url + "&source="+source;
var url = url + "&campaign="+campaign;
var url = url + "&content="+content;
//document.write("url is "+ url);
myImage= new Image();
myImage.src=url;
}
function setcookie(key,tn,path){
index = -1;
var today = new Date();
today.setTime( today.getTime() );
var cookie_expire_date = new Date(today.getTime() + (365* 86400000));
document.cookie="MM_TrackableNumber="+tn+";path=/;expires="+cookie_expire_date.toGMTString();
document.cookie="MM_Keyword="+key+";path=/;expires="+cookie_expire_date.toGMTString();
}
//function to retrive the cookie
function getcookie(){
//plcae your default phone number to show in case cookie is not set
defaultphone="8005551212";
if(document.cookie){ //check if there is a cookie set
index = document.cookie.indexOf("MM_TrackableNumber");
if (index != -1){
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
document.write(formatnumber(document.cookie.substring(namestart, nameend)));
}
else
{
document.write(formatnumber(defaultphone));
}
}
else
{
document.write(formatnumber(defaultphone));
}
}
function get_named_cookie(name)
{
if(document.cookie)
{
index=document.cookie.indexOf(name);
if (index != -1)
{
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
var ret_one = document.cookie.substring(namestart, nameend);
return ret_one;
}
}
}
//function to format the phonenumber to (123) 456-7890
function formatnumber(num)
{
_return="1-";
var ini = num.substring(0,3);
_return+=ini+"-";
var st = num.substring(3,6);
_return+=st+"-";
var end = num.substring(6,10);
_return+=end;
return _return;
}
function getVar(name)
{
get_string = document.location.search;
return_value = '';
do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');
if(name_index != -1)
{
get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
end_of_value = get_string.indexOf('&');
if(end_of_value != -1)
value = get_string.substr(0, end_of_value);
else
value = get_string;
if(return_value == '' || value == '')
return_value += value;
else
return_value += ', ' + value;
}
} while(name_index != -1)
//Restores all the blank spaces.
space = return_value.indexOf('+');
while(space != -1)
{
return_value = return_value.substr(0, space) + ' ' +
return_value.substr(space + 1, return_value.length);
space = return_value.indexOf('+');
}
return(return_value);
}
/*end*/
As simple as this may sound (which I know it's not), I need the <a> tag to do this: <a href="tel:FILL THIS WITH EITHER THE DEFAULT NUMBER OR THE NEW NUMBER DEFINED BY THE TFID URL">

You maybe want to wrap it in a function?
<a onclick="doSomething('123456789')" href="tel:<this phone number needs to be dynamic as well>">Call this number: </a>
<script language="javascript" >
function doSomething(telNumber){
var tel = telNumber;
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if(tn!="")
{
setcookie(key,tn);
}
getcookie();
}
</script>

You can try to store the phonenumber into the ID of the then use this script
<script>
$(document).ready(function () {
$(".clickable").onClick(function() {
var phone = $(this).attr('id')
});
});
</script>
<a class="clickable" id="{variable_phone_number}" href="...."> ... </a>
EDIT: Try this
<a class="clickable" id="+298384858849" href="...."> ... </a>
<script type="text/javascript">
$(document).ready(function () {
var number = $(".clickable").attr('id')
});
</script>
Remember to add the id and the class attributes

Related

How to exclude an anchor tag with a certain href?

I've a JS code that take the UTM and other url parameter so when the user navigate between pages I don't lose their track. The code is working great when the href is a page but not when it's related to an id element
I tried to exclude it in the if statement or to add the parameters after the id.
function getRefQueryParam(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var utmParamQueryString = '',
utmParamQueryStringTrimmed = '',
utm_source = '',
utm_medium = '',
utm_content = '',
utm_campaign = '',
utm_term = '';
(function() {
utm_source = getRefQueryParam("utm_source");
utm_medium = getRefQueryParam("utm_medium");
utm_content = getRefQueryParam("utm_content");
utm_campaign = getRefQueryParam("utm_campaign");
utm_term = getRefQueryParam("utm_term");
gclid = getRefQueryParam("gclid");
fbclid = getRefQueryParam("fbclid");
if (utm_source) {
utmParamQueryString += '&utm_source=' + utm_source;
}
if (utm_medium) {
utmParamQueryString += '&utm_medium=' + utm_medium;
}
if (utm_content) {
utmParamQueryString += '&utm_content=' + utm_content;
}
if (utm_campaign) {
utmParamQueryString += '&utm_campaign=' + utm_campaign;
}
if (utm_term) {
utmParamQueryString += '&utm_term=' + utm_term;
}
if (gclid) {
utmParamQueryString += '&gclid=' + gclid;
}
if (fbclid) {
utmParamQueryString += '&fbclid=' + fbclid;
}
if(utmParamQueryString.length > 0) {
utmParamQueryString = utmParamQueryString.substring(1);
utmParamQueryStringTrimmed = utmParamQueryString;
utmParamQueryString = utmParamQueryString;
}
if (!utmParamQueryString) return;
var navLinks = document.querySelectorAll('a');
navLinks.forEach(function(item) {
if (item.href.indexOf('/') === 0 || item.href.indexOf(location.host) !== -1 ) {
if (item.href.indexOf('?') === -1) {
item.href += '?';
} else {
item.href += '&';
}
item.href += utmParamQueryString;
}
});
})();
So it's searching every anchor tag and after the page uri the code insert the parameters that the current URL have. The issue is that it inserts code even what it's an id call and the call doesn't work anymore because the parameters isn't insert after but in between like so:
utm_source=google&utm_medium=cpc&utm_campaign=test_cpc&utm_term=test #top &utm_source=google&utm_medium=cpc&utm_campaign=test_cpc&utm_term=test
You can try use attribute selector on your querySelectorAll like this:
document.querySelectorAll('a:not([href^="#"])')
This will pick all a tags that the href attribute does not start with #.
You can, of course, try and modify it based on your needs.

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()

Custom JQuery dynamic link creation

I'm pretty new to js and having a hard time figuring out the best way to generate a custom url depending on what links are selected. You can view what I have done here. http://jsfiddle.net/1fz50z1y/26/ I will also paste my info here.
var products = [];
var quantity = [];
qstring = '';
$('input.product-radio, select.products-howmany').change(function() {
var $this = $(this)
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
var qid = $select.val();
var pid = $radio.val();
currentStatus = $radio.prop('checked'),
theString = '';
qString = '';
pString = '';
if (currentStatus) {
products.push(pid);
quantity.push(qid);
if ($product.find('div.quantity').removeClass('q-hidden')) {
//code
}
} else {
products.splice(products.indexOf(pid), 1);
quantity.splice(quantity.indexOf(qid), 1);
$product.find('div.quantity').addClass('q-hidden');
}
if ((products.length > -1) || (quantity.length > -1)) {
if ((products.length === 0) || (quantity.length === 0)) {
console.log("Q Length: " + quantity.length);
pString += products[0];
qString += quantity[0];
console.log("qString = " + quantity);
} else {
pString = products.join('-p');
qString = quantity.join('_q');
if (quantity.length > 1) {
qString = quantity.splice(quantity.indexOf(qid), 1);
pString = products.splice(products.indexOf(pid), 1);
}
console.log("+ Q Length: " + quantity.length);
console.log("ADDING " + "p" + pString + "_q" + qString);
}
if ((qString == 'undefined') || (pString == 'undefined')) {
$('a.options-cart').prop("href", "#");
} else {
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "_q" + qstring + "?destination=/cart");
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "?destination=/cart");
$('a.options-cart').prop("href", "/cart/add/p" + pString + "_q" + qString + "?destination=/cart");
}
}
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});
When you click on the add link icon it displays a drop down where you can select the quantity. So changing the quantity should also update the link and how it is created. I am trying to figure out how to create the link so the end result looks like so.
cart/add/p123_q1?destination=/cart this is how it would look with a single item. Where p = the product ID and q = the quantity. Unclicking the add to cart should remove those items and changing the drop down should update the quantity. If there is more than one item it should append to the link like so. cart/add/p123_q1-p234_q2-p232_q4?destination=/cart and then unclicking or changing quantity on any of those items should reflect the change in the link. I am not sure if I am going about this all wrong but I have been trying forever and many different routes to go about trying to achieve this effect. If anyone could please help me figure this out I would be greatly appreciated!
I was able to get this to work properly using this piece of code. Hope this maybe helps someone.
$('input.product-radio, select.products-howmany').change(function () {
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
$product.find('div.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
$product.find('label.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
var string = $('.product-radio')
.filter(':checked')
.map(function(){
return $(this)
.closest('.product-options-left')
.find('.products-howmany')
.val();
})
.get()
.join('-');
$('a.options-cart').prop("href", "/cart/add/" + string + "?destination=/cart");
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});

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++;
}
}
}

JavaScript isCurrency() failing

hey guys should be a easy one...I have some javascript that is turning my input values into currency values. Problem is it will fail if I try to type in .5 heres is my code:
function handleCurrency(formName,fieldName)
{
var enteredValue = document.forms[formName].elements[fieldName].value;
if ( enteredValue.isCurrency() )
{
alert("This is currency " + enteredValue )
// Put the nicely formatted back into the text box.
document.forms[formName].elements[fieldName].value = enteredValue.toCurrency();
}
}
jsp:
<td><input type="text" name="replacementCost" onchange="handleCurrency('NsnAdd','replacementCost')" value="<ctl:currencyFormat currency='${form.replacementCost}'/>" onkeypress="javascript:return noenter();" <c:if test="${!lock.locked}">disabled="disabled"</c:if> /></td>
How can I make it so that .5 is allowable also to be formatted?
custom javascript:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
function stringIsCurrency()
{
if (patternWithoutCommas.test(this))
{
return true;
}
else if (patternWithCommas.test(this))
{
return true;
}
return false;
}
function stringToCurrency()
{
if (this == '') return this;
var str = this.replace(/[$,]+/g,'');
sign = (str == (str = Math.abs(str)));
str = Math.floor(str*100+0.50000000001);
cents = str%100;
str = Math.floor(str/100).toString();
if (cents<10) cents = "0" + cents;
for (var i = 0; i < Math.floor((str.length-(1+i))/3); i++)
{
str = str.substring(0,str.length-(4*i+3))+','+
str.substring(str.length-(4*i+3));
}
str = '$' + ((sign)?'':'-') + str + '.' + cents;
return str;
}
String.prototype.isCurrency = stringIsCurrency;
String.prototype.toCurrency = stringToCurrency;
basically it needs to allow .5 and not just 0.5
this needs to be updated:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
You have not shown your code for isCurrency.
Here's how I would do it:
function isCurrency( val )
{
return /^\$?(?:\d[\d,]*)?(?:.\d\d?)?$/.test( val );
}
See it here in action: http://regexr.com?3103a
Now that you have provided your code, here's my proposed solution.
While there are many things I would have done differently,
in order to keep the spirit of your code, just change this:
var patternWithCommas = new RegExp("^\\s*\\$?-?(\\d{1,3}){1}(,\\d{3}){0,}(\\.\\d{1,2})?\\s*$");
var patternWithoutCommas = new RegExp("^\\s*\\$?-?\\d+(\\.\\d{1,2})?\\s*$");
to this:
var patternWithCommas = /^\s*\$?-?((\d{1,3}){1}(,\d{3})?)?(\.\d{1,2})?\s*$/;
var patternWithoutCommas = /^\s*\$?-?(\d+)?(\.\d{1,2})?\s*$/;
which would make the dollar amount optional.

Categories

Resources