Hi so I have this jQuery/JS script. That basically takes an encoded URL string and parses it and saves variable values into variables.
Basically what PHP's $_GET does.
function getUrlVars()
{
var map = {};
var parts = window.location.search.replace(/[?&]+([^=&]+)(=[^&]*)?/gi,
function(m,key,value)
{ map[key] = (value === undefined) ? true : value.substring(1); });
return map;
}
Basically this script does what I want. From this URL string:
/autopop.html?Email=test%40test.com&LastName=Test+last&&FirstName=+Test+First
I get the values:
Email = test%40test.com
LastName = Test+last
FirstName = +Test+First
What I want to do is Auto-populate a form on this same page with this information.
(I know what you're thinking a server-side script would be a better solution but the boss says we don't have access to that, trust me, I've tried)
Long story short, here's the rest of my code:
var keys = getUrlVars();
$(document).ready(function(){
var fname = keys['FirstName'].replace(/\+/g , " ").trim();
var lname = keys['LastName'].replace(/\+/g , " ").trim();
var email = decodeURIComponent(keys['Contact0Email'].replace(/\+/g , " ")).trim();
$("#Email").val(email);
$("#FirstName").val(fname);
$("#LastName").val(lname);
});
This code gets the job done. All except for one browser. IE.
IE doesn't support decodeURIComponent or so I've read. In any case, I tried using other functions like decodeURI and escape all producing unwanted results.
My google searches have yielded nothing but, semi-interesting articles (totally off-topic but thought I'd just share that).
No solutions. Can anyone shed some light? How do I make this work on IE?
You have read wrong, decodeURIComponent works just fine in IE, even in IE6.
However, trim doesn't work in IE browsers prior to IE 9 and that's what causing your script to crash.
For working alternative, see the accepted answer here: .trim() in JavaScript not working in IE
Or use the jQuery trim() method as you're already using jQuery anyway.
Related
The following code is used to get URL parameters.
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
<script type="text/javascript">
var url = window.location.protocol + "//" + window.location.hostname;
</script>
The page with the above code is accessed from a link on another page. Within that link i'm passing in a news item ID and Title.
When the page with the above code loads the Title in the URL has %20 in place of all spaces.
I've read up on this and found i need to use decodeURI or decodeURIComponent. I've tried to do this in a number of places and alerted the result in the browser but i can't seem to get rid of the %20 from the title within the URL so its obvious i'm not doing it in the right place.
this is my result....
http://PAGE URL HERE/NewsArchive.aspx?Story=New%20site%20launched&ID=17
I believe i somehow need to include a regular expression of /%20/g,"-" in the replace of the parts variable, however i have next to no knowledge of regex.
Could someone let me know what i need to do as i'm drawing a blank. I've seen a number of similar articles but nothing that explains it to my low level of knowledge.
I also post on SharePoint Stack Exchange as this is being used with SharePoint but i haven't had any answers that have worked for me.
Any help appreciated.
I am not sure I understand the question, but it seems like you just want to retrieve the parameters? If you open the developer console (f12 in chrome) on the page with parameters in the URL you can type window.location and see all the properties of the object. If you type window.location.href you can see the full URI. An easy way to separate this is using .split.
window.location.href.split('?')[1] will give you everything after the ? character. You can do decodeUri(window.location.href.split('?')[1]) to get a normal string.
Just keep in mind the arrays returned by split are zero indexed.
Edit in response to the comment:
The technology you're looking for is history.replaceState. More details here. I would highly recommend a thorough skimming.
history.replaceState(null, "/NewsArchive.aspx", "Story=New-site-launched&ID=17")
Or how would I convert a list of SelectItems to a JavaScript array?
Currently I am trying this:
<h:outputScript>
<!-- Trailing commas valid as per http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5 -->
var possibleOption = [<ui:repeat value="#{bean.mySelectItems}" var="selectItem">"#{selectItem.value}",</ui:repeat>];
var firstOption = possibleOption[0];
</h:outputScript>
And it works, except that firstOption is undefined although possibleOption gets correctly populated when I check in the console. Maybe a timing problem? Is this even valid JSF, and if so, is there a "blocking" version of ui:repeat or something?
Or which other approach would you recommend?
Aaaah, I got it:
actually I was using:
var chosenOption = '#{empty bean.chosenOption ? possibleOption[0] : bean.chosenOption}';
Which is (now) of course wrong, because I was using possibleOption[0] inside the EL expression headbang
Sorry, one should always post the actual code I guess, not some dumbed down showcase ;)
I am working in Classic ASP. The code I'm working with (not my code) was written a very long time ago, perhaps even long before Firefox and Chrome existed.
Anyways, there is the following JavaScript function:
function MM_jumpMenu(targ, selObj, restore) {
eval(targ + ".location ='" + selObj.options[selObj.selectedIndex].getAttribute('value') + "'");
if (restore)
{
selObj.selectedIndex=0;
}
}
That code has all of a sudden stopped working, and I'm trying to figure out why. In Chrome it is giving me the error:
SyntaxError: Unexpected identifier
When I try and run the code, the parameters passed in are as follows:
targ = "parent"
value on selected index of selObj = "edit_details.asp?make=ML&n=&r=DA61CHH&c=Hope Ready Mixed Concrete Ltd - CHY LCV's&cus=HOPEAG02&type=&inc=&id=&fw=&cusid=HOPE03"
restore = 0
Assume code was written solely for IE 6/7 and we're trying to standardise and make it work for all browsers.
eval is evil!! Don't use it!
window[targ].location = selObj.options[selObj.selectedIndex].getAttribute('value');
You have an unescaped single quote in your url.
CHY LCV's&
Espace this:
CHY LCV\'s&
But really, this code is horrible, you should rewrite it if you can.
"value on selected index of selObj " : it has an apostrophe. You'll need to escape that.
I am using the new method: Utilities.formatString()
In the Google Documentation is says it is similar to sprintf %-style.
I searched and read this article about sprintf in PHP.
I cannot seem to get this to work as intended. It is meant to pad this 8 character string with 4 leading zeros. I know there are other ways to do this, But I am trying to get a handle on this sprintf / formatString thing.
var noFormat = "12345678";
var formatted = Utilities.formatString("%012s", noFormat);
I expected the var formatted to be equal to "000012345678".
my debugger tell me that formatted = 0, or sometimes it throws an error..
I am confused.
try it like this :
function xxx(){
var noFormat = '12345678'
var formatted = Utilities.formatString("%012d", noFormat);
Logger.log(formatted)
}
the different parameters that can be used are easy to find on the web, here is an example that explains how the argument must be evaluated in php but the usage is the same.
Logger result :
I am trying to remove linebreaks with JavaScript. It works in all browsers except Internet Explorer (tested in ie7, ie8). I have read a lot of posts but couldn't find a solution to the problem.
Var someText = "Here’s your text.\n It has line breaks that need to be removed.\rUsing Javascript.\r\n";
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
What else can I try?
* EDITED *****
Here's more code and a better explanation of my problem:
function checkLength(fn) {
var fn = document.getElementById(fn);
var fnb = fn.value;
var fnb = fnb.replace(/(\r\n|\n|\r)/gm,"");
var len = fnb.length;
...
What I am trying to do is calculate the number of chars in a textarea. I had to calculate with both Javascript and PHP and because of the linebreaks, PHP and Javascript never came to the same number. When removing the linebreaks, it is all good except in Internet Explorer (when I calculate it with Javascript). fnb.replace doesn't change anything in Internet Explorer for the character count so that is why I am sure it does not remove the linebreaks correctly. In all other browsers it is fine, I can see the difference in the counter after removing the linebreaks in javascript. Only in ie it doesn't change a thing. I have tried a couple of things as well as your suggestions below and the char count before removing the linebreaks and after is the same in ie.
///////// MY ANSWER /////////////////////////////////////
function checkLength(fn) {
var fn = document.getElementById(fn);
var fnb = fn.value;
var fnb = fnb.replace(/(\r\n|\n|\r)/gm,"");
var len = fnb.length;
...
Like Tomalak said, my logic could be improved - Sorry for being new to JavaScript & programming. Maybe Tomalak doesn't make any mistakes but I'm sure everyone else does. We have to make mistakes to learn.
Internet Explorer didn't like
var fn = document.getElementById(fn);
var fnb = fn.value;
I had to change it to:
var fnb = document.getElementById(fn).value;
Even if it wasn't logical, it should have worked. It did work in all browsers except ie. It's a bug.
That was the answer I was looking for.
Try this:
someText = someText.replace(/[\r\n]+/gm,"");
In fact, the regular expression works just fine in at least IE8.0.
The real problem is that you wrote Var instead of var; Firefox lets you get away with it, but IE doesn't.
You don't need the m flag, but you ought to replace with a space instead of nothing.
someText = someText.replace(/[\r\n]+/g,' ');