I am working with the below Javascript function. It only works when the value is a number. I mean it only returns the value if it is a a number. For example:
var ldInstID = getParameterByName("ID")
If ID is a number then it works and assigns the value to the variable but if the ID is a string it is not working. Please help to make this work for a string too.
I am using this on SharePoint list edit page where ID is a list column value. I want to capture another column city and pass it as href query string along with ID.
In the attached images you can see that ldInstID is blank
<!--
Name: dispParent.js
-->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
//get the ID for the Issue from the Query String
// var issueID = getParameterByName("ID");
var ldInstID = getParameterByName("LeadInsitution");
//find the element with the "Add new item" link.
//note that if you have more than one list on your page, this just finds the first one
var anchorElement = $("a[title='Add a new item to this list or library.']");
//modify the "Add new item" link to call the "NewItem2" function and pass in the Issue ID.
//Be sure to put the path to your site below. You can use relative URL to the web application or the FQDN
// $(anchorElement).attr("href","javascript:NewItem2(event,'URL/Lists/Time/NewForm.aspx?IssueID=" + issueID + "');");
// $(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?IssueID=" + issueID + "&LdInst" + LdInst + "');");
$(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?LdInstID=" + ldInstID + "');");
//remove the "onclick" attribute from the anchor element as we aren't using it anymore
$(anchorElement).removeAttr("onclick");
});
// no, I didn't write this function from scratch, I found it at
// http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
// http://www.sharepointhillbilly.com/Lists/Posts/Post.aspx?ID=26
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
variable passed-ID
Variable passed- ldInstID
Get parameter by id from URL:
function getURLParameter(parameterName) {
let result = null, temp = [];
location.search
.substr(1)
.split('&')
.forEach(function (item) {
temp = item.split('=');
if (temp[0] === parameterName)
result = decodeURIComponent(temp[1]);
});
return result;
}
if my url is http://example.com?id1=100&text=my%20text
console.log(getURLParameter('id1')); // 100
console.log(getURLParameter('text')); // "my text"
Related
I have an eCommerce Shopify URL that I need to check for a particular string to determine to change the currency or not.
When the user lands on the site, the URL is e.g. https://www.myshop.com.
In the navigation bar, there are buttons that allow the user to change from the default USD currency to their local currency.
This is a native Shopify feature that requires you to add ?currency=GBP (for example to British Pounds) to the URL.
I check if the string ?currency= exists, and if it does it means the user has selected a currency already, but want to change it again. So I strip out 13 characters from the start of the ? and then replace it with the new currency string.
The problem is if someone lands on the site from an ad, the URL might look like https://www.myshop.com?HkuhJKh6876MJ.
Then I have to change the currency URL to & instead of ?
I can iterate over the string and check for more than 1 ? and then change the URL, but it seems long-winded. Is there a better way to do this?
Below is my current code to check for the ?currency= substring and remove and replace it if it exists with a new currency.
<input type="button" value="Show USD" onclick="showUSD()">
<input type="button" value="Show GBP" onclick="showAUD()">
<script>
function showUSD() {
var changeToCurrency = "USD"; // Set selected currency
checkForSubstring(changeToCurrency); // Check for '?currency=' substring
}
function showGBP() {
var changeToCurrency = "GBP";
checkForSubstring(changeToCurrency);
}
// Check for substring
function checkForSubstring (newCurrency) {
var urlString = window.location.href + "";
var currencySubstring = "?currency=";
if ((urlString.includes(currencySubstring))) {
sliceURL(urlString, currencySubstring, newCurrency);
}
else {
alert("Doesnt contain substring. \nLoading new URL.");
window.location.replace(urlString + currencySubstring + newCurrency);
}
}
// Slice URL
function sliceURL (originalURL, stringToSlice, currency) {
var n = originalURL.indexOf(stringToSlice); // Get position of substring
// Slice substring from URL
var S = originalURL + "";
var bindex = n;
var eindex = n + 13;
S = S.substr(0, bindex) + S.substr(eindex);
// Reload new URL
reloadURL(S, stringToSlice, currency);
}
// Reload URL
function reloadURL(baseURL, stc, currency) {
window.location.replace(baseURL + stc + currency);
}
</script>
The method below will replace the currency value in the query string if there is currency present in window.location.search
let updateCurrency = (CUR)=>{
let queryString = window.location.search;
if(queryString && queryString.length){
queryString = queryString.slice(1);
queryStringData = queryString.split("&");
queryStringData.forEach((query,index)=>{
query = query.split("=")
if(query[0]== 'currency'){
queryStringData.splice(index,1);
queryStringData = queryStringData.join('&')
window.location.search =queryStringData +'¤cy='+CUR
}
});
}
}
I am working in Pardot, if it matters, but have some javascript which will write GA utm parameters to hidden fields.
Unfortunately, if any of the values are blank, it will pass that blank value, and overwrite any existing value. It's important that I am able to overwrite existing values, but only when there is data in the query string.
Is it possible to write default values instead? So for example, a form is submitted with no utm_source, then we write Source="Organic", or something similar.
Here is my code:
<script type="text/javascript">
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
var campaign = getParameterByName('utm_content');
// Put the variable names into the hidden fields in the form. selector should be "p.YOURFIELDNAME input"
document.querySelector("p.source input").value = source;
document.querySelector("p.utm_medium input").value = medium;
document.querySelector("p.utm_campaign input").value = campaign;
document.querySelector("p.utm_content input").value = content;
</script>
Thank you so much for your insight!
Since you make the value "" if empty, and since that is falsey in javascript, just put an if statement before each of the 4 value statements:
if (source) document.querySelector("p.source input").value = source;
In long form, you are saying that if the value exists, then fill in the element with the value. Otherwise, don't do anything:
if (source) {
document.querySelector("p.source input").value = source;
}
I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}
I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here
I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>
I've found several posts alluding to the location.href method. But I can't find anything about how to use the variable on the next page that's opened.
I have a function with a single line of code in an external js file:
function nextPage()
{location.href='page2.html?foo=' + src;}
It's activated by a button in the html file. How do I use this on the next page that's opened? I'm assuming this makes 'foo' available. ('src' is an integer stored as a global variable in the external js file. It's just a number between 1 and 5).
On the next page you can get the value using:
http://page2.html?foo=
location.search
> ?foo=
location.search.substring(1)
> foo=
In Script Tag You Put
var array=location.search;
var data = array.split("foo=");
var divid=data[1];//It has your foo value
if you are using javascript then try this code to get querystring value
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var value = getParameterByName('foo');