I have a javascript function for splitting the url for parameters and then setting the values of text fields with those parameters found. It works perfect... once I refresh the page. How can I get it to fill the text fields when the page loads?
$(function(){
var urlParams = {};
(window.onload = function () {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while((match = search.exec(query)) !== null)
urlParams[decode(match[1])] = decode(match[2]);
})();
window.onload=function(){
var nm= urlParams['name'];
var pn= urlParams['phone'];
var em= urlParams['email'];
document.getElementById('txtName').value=nm;
document.getElementById('txtPhone').value=pn;
document.getElementById('txtEmail').value=em;
}
})
Can anyone help me?
First of all, there is too much window.onload. jQuery's $(function(){}) will be fired when DOM will be ready, and this should be enough for your case. However I tried to reproduce your issue, but the function works for me. Try to remove window.onloads and tell me if it help. Maybe prepare some jsFiddle will be good too.
$(function(){
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while((match = search.exec(query)) !== null)
urlParams[decode(match[1])] = decode(match[2]);
})();
var nm= urlParams['name'];
var pn= urlParams['phone'];
var em= urlParams['email'];
document.getElementById('txtName').innerText=nm;
document.getElementById('txtPhone').innerText=pn;
document.getElementById('txtEmail').innerText=em;
})
Related
How to redirect to page then execute a function with some parameters.
For Example:
Page1.js
if (condition is true) {
window.location.href("Index","Page2");
someFunction();
}
Is there a way to capture the redirection and execute the function in Page2
Kindly help me, Thanks in advance
Please, try this javascript:
Page 1:
if (true) {
window.open("page2.html?myVar1=42&myVar2=66", '_blank');
}
Page 2:
var urlParams = new URLSearchParams(window.location.search);
var v1 = urlParams.get('myVar1');
var v2 = urlParams.get('myVar2');
function someFunction(myVar1, myVar2){
console.log(myVar1);
console.log(myVar2);
}
someFunction(v1, v2);
Page1 Code :
if (condition is true) {
window.location.href = '/yourpage2?act=runfunc';
}
Page2 Code:
<script>
var qParam = getUrlParameter('act');
if (qParam=='runfunc') {
someFunction();
}
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
</script>
I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string
In order to avoid regressions with our analytics tagging, I want to use PhantomJS to automate testing for Adobe Analytics tags.
To do so I want to be able to test 2 things:
Presence of certain js variables declarations in the HTML source
Compare the variables in HTML source with Ajax calls made to Adobe Analytics and ensure they have the same values
Exemple of variable in the HTML source I want to spy on:
<script>s.events="event27";</script>
Here is the js test script I have so far:
"use strict";
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
var page = require('webpage').create();
page.onResourceRequested = function(request) {
var obj = JSON.stringify(request, undefined, 4);
var needle = '2o7';
var url = request.url;
if (url.contains(needle)) {
var calledUrl = decodeURI(decodeURIComponent(url));
console.log(calledUrl);
}
};
page.onResourceReceived = function(response) {
var jsonResponse = JSON.stringify(response, undefined, 4);
};
page.open('http://www.domain.com/page.html', function() {
var s_account = page.evaluate(function () {
return window.s_account;
});
var s_events = page.evaluate(function () {
return window.s.events;
});
phantom.exit();
});
I would like to be able to pass s_account and s_events variables to the onResourceRequested function so that I can assert equality between these 2 variables and _GET params in calledUrl var.
But I can not figure out how to do so. Any help would be appreciated!
I found the way to do it.
I actually get the content of window.s_account from within the onResourceRequested callback:
page.onResourceRequested = function(request) {
var obj = JSON.stringify(request, undefined, 4);
var needle = '2o7';
var url = request.url;
var result = false;
if (url.contains(needle)) {
var s_account = page.evaluate(function () {
return window.s_account;
});
result = true;
var calledUrl = decodeURI(decodeURIComponent(url));
console.log(s_account);
}
};
It might not be the most elegant way to do it however but it works.
i have a code like this and i get "Uncaught TypeError: Cannot call method 'replace' of undefined" in console, im not so good at javascript
<script>
parse_tag = function (str) {
var create_link = function (url, text) {
var link = $("<a>", {
text: text,
href: url,
target: "_blank"
});
return link.prop('outerHTML');
};
// parse username
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
// parse hashtags
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://search.twitter.com/search?q=" + s.replace('#', ''), s);
});
return str;
};
$(document).ready(function() {
var text = $('.desc');
parse_tag(text);
});
</script>
You are calling the function like
var text = $('.desc');
parse_tag(text);
And the function is
parse_tag = function (str) { // <-- str suppose to be a string
var create_link = function(url, text){
// ...
return link.prop('outerHTML');
}
//...
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
}
In this case, str should be string but according to var text = $('.desc'); it's a jQuery object so you can change either var text = $('.desc'); to var text = $('.desc').text(); or make changes in your parse_tag function, otherwise, you'll get error something like object doesn't support this property or method.
Also, you are using two regex as /[#]+[A-Za-z0-9_]+/g, and /[#]+[A-Za-z0-9_]+/g but both are being used on a link, something like
#me`
Because you are returning an a tag using
return link.prop('outerHTML');
So, make changes in your regex too or maybe it's better to use the replace on link's text/href, so make sure you make the changes.
i have for example this URL
www.mypage/SessionPage.aspx?session=session%202#b
using this code i can track the complet URL
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
BUt i would like only to take part of it like session%202
is there a way to do this in JavaScript
Use regular expression
function getSessionId() {
var re = /session=([^&=]+)/g;
var match = re.exec(document.location.href);
if (match) {
var sessionId = match[1];
return sessionId;
}
return null;
}