Javascript get URL params, then trigger click on checkbox - javascript

I got an GET request on a webpage, with multidimensional checkboxes.
The GET request would look like this:
&company_state[AKERSHUS]=AKERSHUS&company_state[AKERSHUS][]=ASKER&company_state[SOGN+OG+FJORDANE]=SOGN+OG+FJORDANE&company_state[SOGN+OG+FJORDANE][]=ASKVOLL
As you can see, company_state is an array, wich again contains an array of values.
Is it possible to use jQuery or plain JS to grab the URL parameters, and trigger a click on the checkboxes with the same name (company_state, company_municipality) and value?
I tried using this, but this doesn't seem to work in this purpose to grab the params.
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
Thanks in advance.
EDIT:
Gives this result in console:

You can parse query string as array,
and then iterate over array and extract key and value.
Code is like this:
function getQueryParameters(str) {
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(
function(n){
return n = n.split("="),this[n[0]] = n[1],this;
}.bind({}))[0];
}
var url = "&company_state[AKERSHUS]=AKERSHUS&company_state[AKERSHUS[]=ASKER&company_state[SOGN+OG+FJORDANE]=SOGN+OG+FJORDANE&company_state[SOGN+OG+FJORDANE][]=ASKVOLL";
var arr = getQueryParameters(url);
for(var a in arr){
console.log("key:" , a.substr('company_state'.length), " value:" , arr[a]);
}
You have here a live example.

Related

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);

user input to URL

I have some url and I need to replace some parts of it with user input from input type="text" and move to new link with button click.
How can I place variables in URL ?
//some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4
i have function, but it place input at the end of url.
function redirect() {
var baseUrl = 'http://google.com.ua/';
document.myform.action=baseUrl + document.getElementById('url').value;
}
<form name="myform" method="post" onsubmit="redirect()">
<input type="text" id="url">
<input type="submit" value="submit">
</form>
You could build out manual query string parsers and constructors, an example would be like:
function parseQuery(qstr){
var query = {};
var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
for (var i in a) { //iterate the array of values
var b = a[i].split('='); //separate the key and value pair
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
}
return query; //returned the parsed query string object
}
function buildQuery(obj){
var str = [];
for(var p in obj) //iterate the query object
if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into the string array
}
return str.join("&"); //take the array of key value pairs and join them on &
}
Then below we take the string that you gave, for example:
var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';
Now we call the parseQuery function on our string.
var obj = parseQuery($str);
Then we iterate the object which was produced from our parseQuery function
Object.keys(obj).forEach(function(k, i) {
switch(k){
case 't1':
obj[k] = 'replacedt1';
break;
case 'service':
obj[k] = 'replacedServices';
break;
case 'host':
obj[k] = 'replacedHost';
}
});
Now the obj variable has the newly updated values. We can rebuild the query using our buildQuery function by passing the object in.
console.log(buildQuery(obj));
Which will produce something like:
createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4
As usual, the jsFiddle
You can use the new URL object (for older browsers, there is a polyfill) :
var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");
alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/
Played with JavaScript a bit, I believe this solves your problem: http://jsfiddle.net/dk48vwz7/
var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";
//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;
//the query string starts with ?, we remove it.
//then, split it by & symbol
var queryvars = anchor.search.replace(/^\?/, '').split('&');
//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
var queryvar = queryvars[i].split('=');
querycontent[queryvar[0]] = queryvar[1];
}
//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need
//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
var fragment = key;
if (querycontent[key]) {
fragment += "=" + querycontent[key];
}
querymerged.push(fragment);
}
anchor.search = querymerged.join("&")
//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;

Javascript: save way to read GET without PHP

I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
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, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.

Difficulty writing a function to extract URL from array

I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories