I am trying to parse multiple href's with one JavaScript function. When I unremark the alert, it works fine. I'm assuming it has something to do with timing but I'm not sure the best way to do this.
I have tried the sleep command to add some sort of pause but that did not work as I expected it.
function pName(selectObject) {
var x = selectObject.value;
var y = selectObject.value.length;
if (x === undefined) {
x = 97;
}
str = '1st page here=' + "'" + x + "'";
//alert(str);
window.location.href = str;
if (y == 0) {
nxt = '2nd page - 1';
} else {
nxt = '2nd page - 2';
}
//alert(nxt);
window.location.href = nxt;
}
It seems like you're trying to set window.location.href to go to str first, and then nxt. Once you navigate to page str, JavaScript will stop execution, and you will be unable to subsequently trigger the redirect to nxt; you cannot have one page navigate to two different pages one after the other.
The obvious solution would be to simply redirect from page 1 to page 3 (nxt) outright, completely ignoring / bypassing page 2 (str). However, if you explicitly want the user to visit both pages, you'll need to set up an automatic redirect on page 2 (str) itself to take you to nxt.
This can be done by simply setting window.location.href = nxt on page 2 (str), though keep in mind that you'll actually need to transfer the logic of setting what nxt evaluates to over to page 2 (str) instead of having it on the initial page 1.
I was able to get this to work using onInput and handling the 2nd piece as it's own function.
onchange="pName(this);sendnew();return false;" onInput="sData(this);sendnew();return false;"
function pName(selectObject) {
var x = selectObject.value;
if (x === undefined) {
x = 97;
}
str = 'Command 1'+ "'" + x + "'" ;
//alert(str);
window.location.href = str;
}
function sData (selectObject) {
var y = selectObject.value.length;
if (y == 0) {
window.location.href = 'Command 2 - B' ;
} else {
window.location.href = 'Command 2 - B' ;
//alert(str);
};
}
Related
I am trying to extract the last part of a URL to track in GTM, but not include added parameters like "?gclid=...".
As in:
https://example.com/m/5f5a0a9472cf844b320b6136/?gclid=1234
I want to just extract the 5f5a0a9472cf844b320b6136.
So far I've used:
function() {
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
But that is giving me the gclid number. This issue is, that parameter only exists on the landing page, not subsequent pages.
so if I were to use length - 2] that won't work once they leave the landing page. It would return the /m/.
How do I escape the "?" string on the landing page?
You can do something like this which will be easier
function (){
paths = window.location.pathname.split("/")
return paths[paths.length-1]
}
maybe this will help
const strs = [
"https://example.com/5f5a0a9472cf844b320b6136/?gclid=1234/",
"https://example.com/m/5f5a0a9472cf844b320b6136/?gclid=1234/",
"https://example.com/m/n/5f5a0a9472cf844b320b6136/",
"https://example.com/m/n/5f5a0a9472cf844b320b6136",
];
strs.forEach((str) => {
// ********************
if (str.includes("?")) {
const parts = str.split("/?")[0].split("/");
console.log(parts[parts.length - 1]);
} else {
const lastChar = str.charAt(str.length - 1);
str = lastChar === "/" ? str.substring(0, str.length - 1) : str;
const parts = str.split("/");
console.log(parts[parts.length - 1]);
}
// ********************
});
Since your using GTM, enable and use the built-in "page path" variable instead, which does not include parameters:
function() {
return {{Page Path}}.split("/").pop();
}
pop() return the last element from the array (it also removes it from the array, which in this case does not matter).
Okay, I found an alternative solution that I thought I'd share. Because that variable string always totals 24 characters, I created a function to look for it.
function getQuoteId() {
var segments = window.location.pathname.split('/');
for (var i = segments.length - 1; i >= 0; i--) {
if (segments[i] && segments[i].length === 24) {
return segments[i];
}
}
return null;
}
This mitigates the trailing "/" as well as the added parameters, and it returns the path I was looking to isolate.
I got this problem. I created a drop down list for choosing the algorithm to work with. It works with the first option but not all of them. Could you please help me?
Thanks in advance
var form1 = document.getElementById('form1');
var form2 = document.getElementById('form2');
var form3 = document.getElementById('form3');
var formArray = [];
formArray.push(form1.innerHTML);
formArray.push(form2.innerHTML);
formArray.push(form3.innerHTML);
//select drop down list//
function changeToCal() {
dropDownList.selectedIndex--;
document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex];
}
//Calculate //
document.getElementById('form').addEventListener("submit",
function(event) {
var fieldy = document.getElementById('fieldy');
var fieldx = document.getElementById('fieldx');
var resultField = document.getElementById('resultField');
var x = parseFloat(fieldx.value);
var y = parseFloat(fieldy.value);
if(!fieldy.value || !fieldx.value) {
alert("Please enter numbers in the fields!");
} else if (dropDownList.selectedIndex = 1) {
var result = (y / 100) * x;
resultField.innerText = "Answer: " + result + "."
event.preventDefault();
} else if (dropDownList.selectedIndex = 2) {
var result = (100 / y) * x;
resultField.innerText = "Answer: " + result + "."
event.preventDefault();
} else if (dropDownList.selectedIndex = 3) {
var result = (y / x) * 100;
resultField.innerText = "Answer: " + result + " %."
event.preventDefault();
} else {
resultField.innerText = "Error"
event.preventDefault();
}
}
);
https://codepen.io/anon/pen/VMZNwQ
This line:
} else if (dropDownList.selectedIndex = 1) {
needs to use a comparison equals operator rather than an assignment equals operator:
} else if (dropDownList.selectedIndex === 1) {
The other if/else clauses are similarly incorrect.
I highly recommend using a decent IDE, it would highlight potential mistakes like this for you.
You will also need to change this:
dropDownList.selectedIndex--;
document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex];
to this:
document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex - 1];
The selectedIndex is live, if you change it using -- that will cause the selected value to be updated.
The way the result is output assumes there is an <h3> with the id resultField but only one of your forms has that id set.
Other miscellaneous suggestions include...
The id attributes need to be unique throughout the document. You currently have 3 hidden forms and you copy around the HTML, leading to 4 elements with each id (resultField, fieldx, fieldy). Whether document.getElementById grabs the right one is down to luck.
Rather than copying around the innerHTML of those forms you'd be better off simply showing and hiding the existing forms using CSS. Alternatively you could use just 1 form and update the relevant text to match the current algorithm.
Listening for the submit event of the form seems odd. Why not use a regular button and listen for the click event?
If you do decide to keep the 3 forms I would suggest registering separate button handlers for each one. The fact that so much of your code is inside a big if/else is a sign that you actually need multiple functions rather than a single function that has to figure out which mode it is in. The code they share could be factored out if appropriate.
There is a field <input> with the id "page", and I got it with document.getElementById('page'). I now try to read the value with getValue(), but nothing happens - what I am doing wrong?
The idea here is the:
Into the input field I entered 12345678910 and then determine that the first five digits are 12345 so the page 12345.html is opened. If I enter 1234581530 it will also open 12345.html. So you need only read the first five digits and then open the file you want, I hope understood my idea.
Sorry for the question, but I am still learning, I would be very grateful if you would give me some examples.
Thanks in advance!
There is no getValue method. You should read value property:
var page = document.getElementById('page').value.substr(0, 5);
location.href = page + '.html';
Demo: http://jsfiddle.net/q8bQc/
You can try something like this.
To get the value (there is no getValue, just value)
var str = document.getElementById('page').value;
To cut it to 5 chars -
str = str.substring(0, 5); // or substr(0, 5)
To open a different link -
location.href = str + '.html';
Or as a single line -
location.href = document.getElementById('page').value.substring(0, 5) + '.html';
You can use sub string to get the first 5 characters:
var str = value = document.getElementById('page').value; // The input
var res = str.substring(0,5); // The first 5 characters
And then some if statement to determine if they equal 12345
if(res == "12345") {
};
Now all you need to do is open the link which can be done like:
window.open("/12345.html","_self")
Which will open the link in the same window
All together:
var str = value = document.getElementById('page').value; // The input
var res = str.substring(0,5); // The first 5 characters
if(res == "12345") {
window.open("/12345.html","_self")
};
First set the element value then cut it and open the link
var value = document.getElementById('page').value;
value = value.substring(0, 5);
window.open(value + '.html') //To Open in a new tab
window.open(value + '.html','_self') //To Open in the same tab
http://jsfiddle.net/52vtQ/
$(function () {
var a;
$("#sub").click(function () {
a = $('#page').val();
alert(a);
});
});
maybe this will help you out with your problem
I'm writing a script that's going to take some information about the website that you visit. I have copied this small portion of my code that I'm struggling with. This part of the code is supposed check if the visited website is using the www prefix and remove that prefix, then there is another part of the code that I haven't pasted stores the domain name in the variable website.
var website = location.hostname;
document.getElementById("displayBefore").innerHTML = website; //test to see the variable
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
document.getElementById("displayTrue1").innerHTML = "true"; //test to see if the conditional was met
for (i = 4; i < website.length; i++) {
website[i - 4] = website[i]; //this is not rewriting anything
document.getElementById("displayPos0").innerHTML = website[i]; //test to see if the for loop has run
}
document.getElementById("displayDuring").innerHTML = website; //test to see the variable
website.splice(0, 4); //this is breaking everything after it
document.getElementById("displayAfter").innerHTML = website; //test to see the variable
}
Here is what's actually being displayed when in those tests when I pull it up in a browser:
WebsiteBeforeFix: www.example.com
True1: true
website[i]: m
WebsiteDuringFix: www.example.com
WebsiteAfterFix:
The two parts of the code that aren't working are the following:
website[i - 4] = website[i];
This is supposed to pretty much shift the letters over 4 spaces to the left(eliminating "www.").
website.splice(0,4);
This is actually causing nothing after it to display at all in any of the code that does work. Can anyone tell me what I may be doing wrong?
splice is an array method, not for strings (they're immutable). Make the variable an array to manipulate it using the split method, and join it back together using the join method:
var websiteStr = location.hostname;
var website = websiteStr.split('');
console.log("displayBefore: " + website.join(''));
if (websiteStr.indexOf("www.") === 0) {
console.log("true");
/*for (var i = 4; i < website.length; i++) {
website[i - 4] = website[i];
console.log("displayPos0: " + website[i]);
}*/
console.log("displayDuring: " + website.join(''));
website.splice(0, 4);
console.log("displayAfter: " + website.join(''));
}
Instead of manipulating HTML, you can use console.log to do basic logging at particular points, which will show up in your browser's console. Anyway, it seems that your for loop doesn't do what you want it to -- splice already removes the "www." prefix.
You can also change this:
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
to this:
if (websiteStr.indexOf("www.") === 0) {
which performs the same thing much more concisely.
With the fixed code, it now displays:
displayBefore: www.google.com
true
displayDuring: www.google.com
displayAfter: google.com
I know that the each() in jQuery is synchronous, but it doesn't seem to behaving that way. When I do this:
$('#findRankBtn').click(function () {
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
var pageNumber = $('#currentPage').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
searchGoogle(searchTerms, pageNumber, websiteURL);
});
function searchGoogle(searchTerms, pageNumber, websiteURL) {
$.getJSON("https://www.googleapis.com/customsearch/v1?key=AIzaSyDPuIrijE0IQ6330vMLN2p-L_4J6y_G60c&cx=013036536707430787589:_pqjad5hr1a&q=" + searchTerms + "&alt=json&start=" + pageNumber,
function (recievedData) {
//console.log(recievedData);
$.each(recievedData.items, function (i, item) {
$('#resultsDiv').append('<p class="resultLink">' + item.link + '</p>');
var linkAddress = $('.resultLink:last').text();
if (linkAddress.indexOf(websiteURL) !== -1) {
alert('found');
$('.resultLink:last').attr('class', 'yourLink');
$('#ifFound').attr('value', 'true');
}
});
var ifFound = $('#ifFound').val();
var currentPage = $('#currentPage').val();
var nextPage = CurrentPage + 1;
if (ifFound == 'false') {
//INCREMENT PAGE
$('#currentPage').attr('value', nextPage);
//GRAB DATA AGAIN
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
//SEARCH GOOGLE
searchGoogle(searchTerms, nextPage);
}
});
}
Basically if it doesn't find the desired link on the first page of results, it should go on to the next page. I have a working fiddle for just the first page here: http://jsfiddle.net/p8DY3/1/
so how can I get searchGoogle() to run until it finds what it's looking for?
Maybe there's a better way of going about it that's in the Google API that I don't know about?
Sorry if my question is amateur, I've only begun to learn JavaScript on my own a month ago.
First you should make sure you are not hitting some sort of rate limit from Google. Look at your Network tab to see if the requests are coming back correctly.
First issue I see is bad math.
var currentPage = $('#currentPage').val(); is a string
Here var nextPage = CurrentPage + 1; you are treating it as a number.
You got to convert the string to a number before you add to it. You are doing string concatenation!.
var nextPage = parseInt(CurrentPage,10) + 1;
NITPICKS
Do not store things in inputs. Use variables, it will make things go so much faster. DOM lookup/manipulation is slow.
Why are you reinventing addClass and val()
$('.resultLink:last').attr('class', 'yourLink');
$('#currentPage').attr('value', nextPage);
should be
$('.resultLink:last').addClass('yourLink');
$('#currentPage').val(nextPage);
Why are you grabbing the search terms and website url again? You already have them passed into the function?
Finally your problem
searchGoogle(searchTerms, nextPage); <-- What are you missing here?
function searchGoogle(searchTerms, pageNumber, websiteURL) { <--what it is expecting
You are passing in 2 things when it wants 3.