dynamic a href using url parameter

Discussion in 'Javascript' started by Ryan Goodman, Jan 3, 2009.

  1. Ryan Goodman

    Ryan Goodman Guest

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


    *** Sent via Developersdex http://www.developersdex.com ***
    Ryan Goodman, Jan 3, 2009
    #1
    1. Advertising

  2. 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.
    Jeremy J Starcher, Jan 3, 2009
    #2
    1. Advertising

  3. 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.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
    Thomas 'PointedEars' Lahn, Jan 3, 2009
    #3
  4. 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
    Thomas 'PointedEars' Lahn, Jan 3, 2009
    #4
  5. "Ryan Goodman" <> wrote in message
    news:495fb0ec$0$87067$...
    >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
    Trevor Lawrence, Jan 3, 2009
    #5
  6. Thomas 'PointedEars' Lahn <> 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).
    Eric B. Bednarz, Jan 4, 2009
    #6
  7. Ryan Goodman

    SAM Guest

    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;
    }
    }
    SAM, Jan 4, 2009
    #7
  8. 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
    Laurent vilday, Jan 4, 2009
    #8
  9. Eric B. Bednarz wrote:
    > Thomas 'PointedEars' Lahn <> 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
    Thomas 'PointedEars' Lahn, Jan 4, 2009
    #9
  10. Ryan Goodman

    Jorge Guest

    On Jan 3, 8:52 pm, Thomas 'PointedEars' Lahn <>
    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.
    Jorge, Jan 4, 2009
    #10
  11. "Laurent vilday" <> wrote in message
    news:49608191$0$31444$...
    > 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.


    [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 ??!!

    --
    Trevor Lawrence
    Canberra
    Web Site http://trevorl.mvps.org
    Trevor Lawrence, Jan 4, 2009
    #11
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. CRON
    Replies:
    24
    Views:
    200,435
    Adrienne Boswell
    Jun 20, 2006
  2. Soren Vejrum
    Replies:
    4
    Views:
    519
    Lasse Reichstein Nielsen
    Jul 5, 2003
  3. saiho.yuen
    Replies:
    3
    Views:
    405
    kaeli
    Sep 14, 2004
  4. Replies:
    2
    Views:
    441
  5. kelvlam
    Replies:
    6
    Views:
    336
    kelvlam
    Jul 18, 2006
Loading...

Share This Page