IE JavaScript params and populating input field - javascript

I'm trying to return c= and then have it write into an input field and the submit the value.
var x = window.external.menuArguments.location.href; // IE Get URL Code
alert(x);
// http://site.com/design/page.html?c=235783&p=irol-IRHome
// this code below populates a html pop that is created on popup.
var parentwin = external.menuArguments;
var doc = parentwin.document;
var sel = doc.selection;
var rng = sel.createRange();
var str = new String(rng.text);
var html = new String(rng.htmlText);
var ops = "width=650,height=410,status=0,toolbar=0,menubar=0,resizable=1";
viewSourceWin = parentwin.open("about:blank","viewselectionscr",ops);
// open document for further output
viewSourceWin.document.open();
viewSourceWin.document.write("$(document).ready(function() {");
viewSourceWin.document.write("load = ?;");
viewSourceWin.document.write("$('#cmid').val(load);$('.go').click();");
viewSourceWin.document.write("});");
viewSourceWin.document.write("<input id='cmid'/><button class='go'>Go</button>")");

You want the location.search, like:
var query = window.location.search.substring(1); // use substring to remove the leading '?'
var keyValues = query.split('&'); // split apart
var params = {};
for (var kv in keyValues) {
var parts = kv.split('=');
params[ parts[0] ] = parts[1];
}
var c = params['c'];
//... do whatever you need
Of course there is a jquery plugin or three and some fancier regular expressions that you could also use.

Related

Adding a dummy parameter to refresh a script

I'm trying to create a dummy parameter to update a cell colour checking script, however whenever I add an extra parameter, I get an error in that cell. Range not found Line 7.
I think it might be something to do with the regexp but I can't figure out how to fix it.
function countColoredCells(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var rangeA1Notation = formula.match(/\((.*)\,/).pop();
var range = activeSheet.getRange(rangeA1Notation);
var bg = range.getBackgrounds();
var values = range.getValues();
var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
var colorCell = activeSheet.getRange(colorCellA1Notation);
var color = colorCell.getBackground();
var count = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] == color )
count=count+1;
return count;
};
I got this code from: http://igoogledrive.blogspot.com/2015/11/google-spreadsheet-count-of-colored.html

How to save strings from part of url?

Given the following URL:
https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States
How can I save three vars:
var date1: "2015";
var date2: "2017";
var loc = "United States";
Note: we have two dates with a + symbol in the url 2015+2017 and we need to split them. And has a dash in the url United-States and we need it as United States
This is what I am trying:
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");
Also, I need to update the URL again for other reasons once the page is loaded, and I do:
history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14='+dateSplit+'&usp-custom-8='+loc);
But the url is duplicated
https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States/?usp-custom-14=2015,2017&usp-custom-8=United-States
You can split the url on ? and use pop() to return the last member of the resulting array, which would be the entirety of your query string.
From there, you could split it into key-value pairs by splitting it first on &, and then on =.
I've put this in a function so that you can simply do getParam("my-url-parameter") when needed. Using this, and then handling the + and - on your specific parameters, you should be able to get what you want quite easily.
It should also be reusable wherever needed.
function getParam(key) {
//var url = window.location.href; (Doesn't work on StackOverflow, but would be used in your real environment)
var url = "https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var querystring = url.split("?").pop();
var params = {};
querystring.split("&").forEach((i) => params[i.split("=")[0]] = i.split("=")[1]); //Create key-value pairs
return params[key] || null;
}
var uspCustom14 = getParam("usp-custom-14").split("+");
var date1 = uspCustom14[0];
var date2 = uspCustom14[1];
var country = getParam("usp-custom-8").replace(/\-/g, ' ');
console.log(`Date 1: ${date1},`, `Date 2: ${date2},`, `Country: ${country}`);
For your second issue, you can remove the query string and re-add it with the proper values:
var urlDates = getParam("usp-custom-14").replace('+',',');
var urlCountry = getParam("usp-custom-8");
history.replaceState('data to be passed', 'Title of the page', `${window.location.href.split("?")[0]}?usp-custom-14=${urlDates}&usp-custom-8=${urlCountry}`);
This should give you what you want while keeping it as close to your original code as I could. You can safely split a string with a "+" in it. You had the "?" and "=" splits in the wrong order.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.split('?')[1];
var params = hashes.split('&');
for(var i = 0; i < params.length; i++) {
hash = params[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");
var str ="https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var split = str.split('usp-custom-14=');
var firstDate = split[1].split('+')[0];
var secondDate = split[1].substring(split[1].lastIndexOf("+")+1,split[1].lastIndexOf('&'));
var country = split[1].substring(split[1].lastIndexOf("=")+1,split[1].length-1).replace('-',' ');
console.log(firstDate);
console.log(secondDate);
console.log(country);

Adding values concatenating

Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.

Javascript replace with /gi and array-iterator

how can i make this work:
var storedValues = $('<table class="table_groessentabelle_custom"></table>');
// contains excel paste content from Libreoffice
$('textarea[name=excel_data]').bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text/html');
storedValues.append(pastedData);
});
//localisation - tables (just a subset)
var de = ["Größe","Höhe","Weite","Damen","Herren","Kinder",];
var fr = ["Pointure","Hauteur","Largeur","Femme","Homme","Enfants"];
var de_storedvalues = JSON.parse(JSON.stringify( storedValues.html() ));
var fr_storedvalues = JSON.parse(JSON.stringify( storedValues.html() ));
for (var i = 0; i < de.length; i++) {
// doesnt work, no fields are translated
fr_storedvalues = fr_storedvalues.replace(/de[i]/gi,fr[i]);
}
it works without the /gi flag but only transates the first entry of a given variable. if there is more than one entry, the rest stays in german.
Thanks in advance,
Michael
var find = de[i];
var regex = new RegExp(find, "g");
fr_storedvalues = fr_storedvalues.replace(regex,fr[i]);

How do I get multiple comma separated values from URL

I have a URL like:
http://www.mysite.com/index.html?x=x1&x=x2&x=x3
How do I got the values like below, using JavaScript or JQuery:
var x='x1,x2,x3'
var url = "http://www.mysite.com/index.html?x=x1&x=x2&x=x3";
var params = url.match(/\?(.*)$/)[1].split('&');
var values = [];
for(var i=0; i<params.length; i++){
values.push( params[i].match(/=(.*)$/)[1] );
}
var result = values.join(","); // "x1,x2,x3"
EDIT: Here is a better solution that lets you select the parameter you want. This is something that I have found buried inside one of my projects, and I didn't write every part of it.
function $_GET(param) {
var query = window.location.search.substring(1);
var vars = query.split('&');
var values = [];
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (urldecode(pair[0]) == param) {
values.push(urldecode(pair[1]));
}
}
return values.join(",");
}
// Decode URL with the '+' character as a space
function urldecode(url) {
return decodeURIComponent(url.replace(/\+/g, ' '));
}
If you directly hit url you can use it as
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
This will hit current url to search data for given parameters.
If you want to manually create url then hit search then
var url = "http://www.mysite.com/index.html";
window.location.href = url;
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
Now you can search values, as per requirement.
I think what you need is PURL. Please refer https://github.com/allmarkedup/purl for detailed usage and guidelines
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
read here http://javascriptproductivity.blogspot.in/2013/02/get-url-variables-with-javascript.html
You can easily find query string in jquery using jquery split
Try this function to get Query String as a array object:
function getUrlVars()
{
var vars = [];
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[1]);
}
return vars;
}
The function returns an array/object with your URL parameters and their values. So, you can use jquery .join() to convert it into comma separated values:
var result = vars.join(",");
Try in jsfiddle
Maybe use Regex:
var s = window.location.search;
var foo = s.match(/x=([0-9a-zA-Z]+)/g).join(",").replace(/x=/g, ""); // x1,x2,x3

Categories