Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > dynamic a href using url parameter

Reply
Thread Tools

dynamic a href using url parameter

 
 
Ryan Goodman
Guest
Posts: n/a
 
      01-03-2009
I have searched high and low on the web and have been hacking at it for
quite a few hours and figured I would turn to the experts.

Functionally, I want to consume a parameter from a URL and place it
inside of a new A HREF. In my example the parameter is "partnerid"
http://ryangoodman.net?partnerid=xyz

Does someone have anything in their code toolbox to do this? I have
this code which I found on the web that takes "partnerid" and places it
in a form, which fills in half of the functionality. The other half, is
using the same parameter and putting it at the end of an A HREF. I
appreciate any help.

-----------Code-------------

<script language="JavaScript">

<!-- Begin
function getParams() {
var idx = document.URL.indexOf('?');
var params = new Array();

if (idx != -1) {
var pairs = document.URL.substring(idx+1,
document.URL.length).split('&');
for (var i=0; i<pairs.length; i++) {
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}

params = getParams();

// End -->
</script>


<form name="myForm" action="submit.cgi" >
Passed Variable 'Name': <input type="text" name="edtName">
</form>

<script language="JavaScript">
<!-- Begin
pvName = unescape(params["partnerid"]);
document.myForm.edtName.value = pvName;
// End -->
</script>

-----------Code-------------


*** Sent via Developersdex http://www.developersdex.com ***
 
Reply With Quote
 
 
 
 
Jeremy J Starcher
Guest
Posts: n/a
 
      01-03-2009
On Sat, 03 Jan 2009 18:39:40 +0000, Ryan Goodman wrote:

> I have searched high and low on the web and have been hacking at it for
> quite a few hours and figured I would turn to the experts.
>
> Functionally, I want to consume a parameter from a URL and place it
> inside of a new A HREF. In my example the parameter is "partnerid"
> http://ryangoodman.net?partnerid=xyz
>
> Does someone have anything in their code toolbox to do this? I have
> this code which I found on the web that takes "partnerid" and places it
> in a form, which fills in half of the functionality. The other half, is
> using the same parameter and putting it at the end of an A HREF. I
> appreciate any help.


While this *can* be done in Javascript, I strongly recommend using a
server-side option, to keep this functional for those not running
Javascript.

 
Reply With Quote
 
 
 
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-03-2009
Ryan Goodman wrote:
> <script language="JavaScript">


Invalid, deprecated. At least <script type="text/javascript"> is required.

> <!-- Begin


Error-prone nonsense.

> function getParams() {


This code style makes it harder to distinguish between function declarations
and function expressions. You should add a newline before the `{', and
indent it so that it is in the same column as the `f' of `function'.

> var idx = document.URL.indexOf('?');


Good of you to use the standards compliant document.URL property in
place of the proprietary window.location.search property (or even the
deprecated document.location.search).

> var params = new Array();


Since the property names are not necessarily numbers, you want an Object
object, not an Array object, here:

var params = {};

or (slightly more compatible)

var params = new Object();

> if (idx != -1) {
> var pairs = document.URL.substring(idx+1,
> document.URL.length).split('&');


However,

var
m = document.URL.match(/\?[^#]+/),
pairs = m ? m[0].split(/[&;]/) : [];

is more efficient, less error-prone, and more compatible as to the parameter
style.

> for (var i=0; i<pairs.length; i++) {


Merely a matter of style, but I recommend to write

for (...)
{
...
}

instead.

> nameVal = pairs[i].split('=');

^^^^^^^^^
Assignment to undeclared identifier --> creation of global property.
Always use

var nameVal = ...

> params[nameVal[0]] = nameVal[1];


You have to unescape here left-hand side of the assignment, else the
parameter of property accesses have to be escaped for it to work.

For coding efficiency, you can unescape here right-hand side, too.

In any case you should use unescape() only as a fallback and prefer
decodeURIComponent() instead which is well-standardized and Unicode-safe.

> }
> }
> return params;
> }
>
> params = getParams();


Undeclared global property.

> // End -->


Error-prone nonsense.

> </script>
>
>
> <form name="myForm" action="submit.cgi" >


The form probably does not need a name.

> Passed Variable 'Name': <input type="text" name="edtName">


type="text" is superfluous, "text" is the default attribute value.

> </form>


A submit button is missing.

> <script language="JavaScript">
> <!-- Begin


See above.

> pvName = unescape(params["partnerid"]);

[1]^^^^^^ ^^^^^^^^[2]

[1] Undeclared global property.
[2] See above. Use decodeURIComponent() instead.

> document.myForm.edtName.value = pvName;


document.forms["myForm"].elements["edtName"].value = pvName;

is standards-compliant, backwards-compatible, and less error-prone.
However, if there is only one supposed to be in the document, the approach
that shares all these properties,

document.forms[0].elements["edtName"].value = pvName;

suffices.

> // End -->
> </script>


See above.

Also, the `script' element after the form should be replaced by a call to a
function having its content as its body, declared within the `head' element,
in the `onload' attribute of the `body' element where one can be quite sure
that the DOM tree is complete.


PointedEars
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-03-2009
Thomas 'PointedEars' Lahn wrote:
> Ryan Goodman wrote:
>> for (var i=0; i<pairs.length; i++) {

>
> Merely a matter of style, but I recommend to write
>
> for (...)
> {
> ...
> }
>
> instead.


And

for (var i = pairs.length; i--
{
...
}

is more efficient here. If order mattered,

for (var i = 0, len = pairs.length; i < len; i++)
{
...
}

would be more efficient than your way.


PointedEars
 
Reply With Quote
 
Trevor Lawrence
Guest
Posts: n/a
 
      01-03-2009
"Ryan Goodman" <(E-Mail Removed)> wrote in message
news:495fb0ec$0$87067$(E-Mail Removed)...
>I have searched high and low on the web and have been hacking at it for
> quite a few hours and figured I would turn to the experts.
>
> Functionally, I want to consume a parameter from a URL and place it
> inside of a new A HREF. In my example the parameter is "partnerid"
> http://ryangoodman.net?partnerid=xyz
>
> Does someone have anything in their code toolbox to do this? I have
> this code which I found on the web that takes "partnerid" and places it
> in a form, which fills in half of the functionality. The other half, is
> using the same parameter and putting it at the end of an A HREF. I
> appreciate any help.


I use this script
function qsobj(parm) {
// get url string after '?' and split by "&" into an array
var qpairs = document.location.search.substring(1).split("&") ;

// split qpairs[parm] by "=" into an array
var qvbl = qpairs[parm].split("=") ;

// return result if it exists, else blank string
return qvbl[1] ? unescape(qvbl[1].replace(/%20|\ +/g," ")) : null ;
}
// ---- end qsobj() ------------

It works for me, but no doubt the experts will find fault with it.

To place in <a href>, I would do it in JS. If the parameter is itself a URL,
try (not tested, but I have used similar)
document.write
( '<a href="' + qsobj(0) + '">' )

If the parameter is a title, try (again not tested)
document.write
( '<a href="xxxx.html" title=" + qsobj(0) + '">' )

Or can use the href properties,
e.g in HTML <a href="" title="" id="myhref">
and in JS
var x= document.getElementByID("myhref");
x.href =qsobj(0);
/* or */
x.title = qsobj(0);

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org


 
Reply With Quote
 
Eric B. Bednarz
Guest
Posts: n/a
 
      01-04-2009
Thomas 'PointedEars' Lahn <(E-Mail Removed)> writes:

> Ryan Goodman wrote:
>> <script language="JavaScript">

>
> Invalid, deprecated. At least <script type="text/javascript"> is required.


You don’t tell what it is ‘required’ for. Execution as ‘javascript’?
Compatibility with NN4 peculiarities? Your guess is better than mine,
but the OP may want to know.

>> <!-- Begin

>
> Error-prone nonsense.


If the client has e.g. a PDF generator (personally last seen ~2005,
backwards compatibility right here is usually more hardcore) that cannot
cope without the HTML style comment declarations, not using them would
probably be considered as error-prone nonsense and considered
non-billable hours (an average project manager would distribute his to
yours, unless you come up with project related reasons).

>> function getParams() {

>
> This code style makes it harder to distinguish between function declarations
> and function expressions. You should add a newline before the `{', and
> indent it so that it is in the same column as the `f' of `function'.


A good rule of thumb is, if somebody does not press his
personal/project/corporate coding style on you, be so kind to return the
favour (tips to make code snippets more readable in usenet messages are
always useful, of course).
 
Reply With Quote
 
SAM
Guest
Posts: n/a
 
      01-04-2009
Le 1/3/09 7:39 PM, Ryan Goodman a crit :
> I have searched high and low on the web and have been hacking at it for
> quite a few hours and figured I would turn to the experts.
>
> Functionally, I want to consume a parameter from a URL and place it
> inside of a new A HREF. In my example the parameter is "partnerid"
> http://ryangoodman.net?partnerid=xyz


window.onload = function() {
var partnerid = self.location.toString().split('=')[1];
var lks = document.links;
for(var i=0, n= lks.length; n>i; i++)
if(lks[i].href) lks[i].href += '?partnerid='+partnerid;
}


> Does someone have anything in their code toolbox to do this? I have
> this code which I found on the web that takes "partnerid" and places it
> in a form, which fills in half of the functionality. The other half, is
> using the same parameter and putting it at the end of an A HREF.



function getParam( param ) {
var params = self.location.toString().split('?')[1].split('&');
if(params.length) {
for(var i=0, n=params.length; n>i; i++)
if(params[i].indexOf(param)>=0)
return params[i].split('=')[1];
}
return false;
}

window.onload = function() {
var param = getParam('partnerid');
if(param) {
var lks = document.links;
for(var i=0, n= lks.length; n>i; i++)
if(lks[i].href) lks[i].href += '?partnerid='+param;
}
}
 
Reply With Quote
 
Laurent vilday
Guest
Posts: n/a
 
      01-04-2009
Thomas 'PointedEars' Lahn :
> Ryan Goodman :
>> Passed Variable 'Name': <input type="text" name="edtName">

>
> type="text" is superfluous, "text" is the default attribute value.


Oh come on, stop with this argument, you may be right in javascript
terms, but you are wrong in terms of CSS selectors, the type="text" may
be here for a *very* good reason. The fact that *you* can not see a
valid one doesn't mean it is always superflous.

<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
input[type="text"] { color:red }
</style>

</head>
<body>

<form action="#" method="get" onsubmit="return false">
<input type="text" name="ok" value="OK">
<input name="not_ok" value="not_OK">
</form>

</body>
</html>

IE7 and IE8b1 : "ok" and "not_ok" are both red
FF3, OP9, chrome : "ok" is red, "not_ok" is not red

Since this "issue" is *NOT* javascript related, can you please stop
using this old argument everytime in here. Thanks !

Or in other way to say it, why do you repeat yourself a *lot* everytime
you can with easy and useless arguments ? (language="javascript"
deprecated, don't use <!--, type="text" superflous, window.onload ouch,
etc.) ?

While you are refusing to reiterate criticals issues with more
understandable words when needed ? (you missed the point, utter
non-sense, score adjusted, etc.)

--
laurent
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-04-2009
Eric B. Bednarz wrote:
> Thomas 'PointedEars' Lahn <(E-Mail Removed)> writes:
>> Ryan Goodman wrote:
>>> <script language="JavaScript">

>> Invalid, deprecated. At least <script type="text/javascript"> is
>> required.

>
> You don’t tell what it is ‘required’ for. Execution as ‘javascript’?


Valid markup, of course. (BTW, your apostrophe looks like a typographical
closing single quote here.)

> Compatibility with NN4 peculiarities?


Of course not.

> Your guess is better than mine, but the OP may want to know.


I expect posters to be intelligent people who ask about why it is invalid or
why it is required iff their STFW did not help.

>>> <!-- Begin

>> Error-prone nonsense.

>
> If the client has e.g. a PDF generator (personally last seen ~2005,
> backwards compatibility right here is usually more hardcore) that cannot
> cope without the HTML style comment declarations,


It is _not_ "a HTML style comment declaration". It is an SGML/XML
declaration that is includes a comment (delimited by `--'s) but is
otherwise empty.

> not using them would probably be considered as error-prone nonsense and
> considered non-billable hours (an average project manager would
> distribute his to yours, unless you come up with project related
> reasons).


Borken user agents are no excuse for error-prone code. Not the code must
care for the borken user agent, but either the borken user agent must be
updated so as to comply with Web standards, or a better program should be
used instead.

>>> function getParams() {

>> This code style makes it harder to distinguish between function
>> declarations and function expressions. You should add a newline before
>> the `{', and indent it so that it is in the same column as the `f' of
>> `function'.

>
> A good rule of thumb is, if somebody does not press his
> personal/project/corporate coding style on you, be so kind to return the
> favour (tips to make code snippets more readable in usenet messages are
> always useful, of course).


"should" indicates a strong recommendation, as you should know.


PointedEars
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      01-04-2009
On Jan 3, 8:52*pm, Thomas 'PointedEars' Lahn <(E-Mail Removed)>
wrote:
>
> * for (var i= 0, len= pairs.length; i < len; i++) { ... }
>
> would be more efficient than your way.



Yeah, faster by a few nanoseconds. A few nS here, a few nS there...

--
Jorge.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
using href="#" vs href="javascript:func()" ? kelvlam Javascript 6 07-18-2006 03:59 PM
href="javascript:func()" vs href="#" onclick="javascript:func()" CRON HTML 24 06-20-2006 08:05 PM
onClick method question (this.href and document.location.href) yogesh.bhardwaj@gmail.com Javascript 2 02-03-2005 02:38 PM
difference between location.href and window.location.href? saiho.yuen Javascript 3 09-14-2004 06:51 PM
Problem: Setting MSIE iframe innerHTML change relative href/src to absolute href/src Soren Vejrum Javascript 4 07-05-2003 01:47 PM



Advertisments