dynamic a href using url parameter

R

Ryan Goodman

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.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-------------
 
J

Jeremy J Starcher

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.
 
T

Thomas 'PointedEars' Lahn

Ryan said:
<script language="JavaScript">

Invalid said:
<!-- 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.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.

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
 
T

Thomas 'PointedEars' Lahn

Thomas said:
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
 
T

Trevor Lawrence

Ryan Goodman said:
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);
 
E

Eric B. Bednarz

Thomas 'PointedEars' Lahn said:
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.
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).
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).
 
S

SAM

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.href) lks.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.indexOf(param)>=0)
return params.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.href) lks.href += '?partnerid='+param;
}
}
 
L

Laurent vilday

Thomas 'PointedEars' Lahn :
Ryan Goodman :

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.)
 
T

Thomas 'PointedEars' Lahn

Eric said:
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.
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.
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
 
J

Jorge

  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...
 
T

Trevor Lawrence

Laurent vilday said:
Thomas 'PointedEars' Lahn :

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.

[snip]

Yes, these criticisms do tend to annoy. I once wrote "If it works, use it "
and I was blown out of the water for not being rigorous enough.

On a similar topic, I read somewhere that <script></script> will generally
work OK, because "type="text/javascript" is the default. So if one were to
*omit* something which is a default (type="text/javascript"), would it be
criticised, whereas *using* something that is also a default (type="text")
is also criticised? The purists also insist on using window.alert rather
than alert, on the (to my mind) spurious grounds that alert without a
qualifier could be a local function . Really ??!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top