SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru ripcurlksm's Avatar
    Join Date
    Aug 2004
    Location
    San Clemente, CA
    Posts
    859
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Retreive url variables and put into form elements

    I am trying to pull two variables from a url and insert them into the appropriate text fields in a html form.

    URL:
    orderform.php?shape=Longboard&model=Cutter

    I have this javascript, which searches the url string, HOWEVER it pulls the string into one variable. ie - Shape: LongboardCutter - INSTEAD OF: Shape: Longboard - Model: Cutter.

    Code:
    <script language="JavaScript">
    document.form1.shape.value = location.search.substring(1);
    </script>
    [b]How do I get the javascript to pull the two variables seperately?[\b]

    Regards,
    Kevin
    Last edited by ripcurlksm; Apr 29, 2005 at 23:10.

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2004
    Posts
    1,647
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function getURLParam(numt) {
    var strReturn, strHref, aParam, strQueryString, aQueyString, i;
    strHref = window.location.href;
    if (strHref.indexOf("&") > -1) {
    strQueryString = strHref.substr(strHref.indexOf("&")).toLowerCase();
    aQueryString = strQueryString.split("&");
    for (i = 0; i < aQueryString.length; i++) {
    if(aQueryString[i].indexOf(numt + "=") > -1) {
    aParam = aQueryString[iParam].split("=");
    strReturn = aParam[1];
    }
    }
    }
    return strReturn;
    }
    
    document.form1.shape.value = getURLParam(shape);
    document.form1.model.value = getURLParam(model);
    cheers

  3. #3
    SitePoint Zealot
    Join Date
    Apr 2005
    Location
    Helsingborg, Sweden
    Posts
    168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why use javascript to search the URL when you are using php?

    <form action="orderform.php" method="post">
    <?php
    echo "<input type =\"text\" name=\"shape\" value=\"".$_GET['shape']."\" />\n";
    echo "<input type =\"text\" name=\"model\" value=\"".$_GET['model']."\" />\n";
    ?>
    <input type="submit" name="submit" value="Order" />
    </form>

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    reminder, your function seems to be correct, however with the power of regular expressions it could be much simpler:

    Code:
    function getURLParam(name) {
    	var m = location.search.match(
    		new RegExp("[?&]" + name + "=([^&]+)"));
    	return m ? unescape(m[1]) : "";
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •