Forum Moderators: open

Message Too Old, No Replies

Pre-populate form fields with query string paramaters

         

SilverLining

1:22 pm on May 17, 2011 (gmt 0)

10+ Year Member



Hi,

I'm using a reg ex script to separate query string values, but can't get the values displayed in the form input fields. I'm not sure that one can use JavaScript document.write inside the form field value. The format of the url should be something like this example.htm?a=aValue&b=bValue

Here is the HTML:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Tuesday</title>
<script>
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
var a_value = getQuerystring('a');
var b_value = getQuerystring('b');
$("#a").val(a_value);
if(qs == null)
return default_;
else
return qs[1];
}
</script>
</head>
<body>
<form id="myform">
<table>
<tr><td>Val A: </td><td><input type="text" id="a" value=""/></td></tr>
<tr><td>Val B: </td><td><input type="text" id="b" value="" /></td></tr>
</table>
</form>
</body>
</html>

I have tried to update the form field with
$("#a").val(a_value);
. It would be nice to get this done with jQuery. Am I doing it completely wrong or am I on the right track?

Also, the form action should be POST, to post the new data, but will I require a GET action to pull in the parameters?

The pre-populated form fields will be read-only. There will be additional fields that will be filled out.

Thank you an advance.

Fotiman

2:11 pm on May 17, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



One can not use document.write inside a form field value. One SHOULD NOT use document.write ever.

In addition, you should not be using JavaScript for this. Users with JavaScript disabled won't be able to use it. You should use a server side processing language instead (PHP, ASP, etc.).

If the values were submitted via POST, then you will not have access to them via JavaScript (POST values do not get passed in the query string).

SilverLining

6:48 pm on May 17, 2011 (gmt 0)

10+ Year Member



Thanks Fotiman.

I understand your point, however in this case the website in question relies heavily on JavaScript and is the best language to use.

Could you assist me with the JavaScript / jQuery code, please?

You mention that one should never use document.write. Is this because the DOM cannot be updated?

birdbrain

7:01 pm on May 17, 2011 (gmt 0)



Hi there SilverLining,

Bearing in mind that javascript is not my forte, does this example help....

Monday:-


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">

<title>Monday</title>

</head>
<body>

<div>
<a href="tuesday.html?a=aValue&amp;b=bValue">Tuesday</a>
</div>

</body>
</html>


Tuesday:-


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">

<title>Tuesday</title>

<style type="text/css">
#inp1,#inp3 {
background-color:#ccc;
}
</style>

<script type="text/javascript">
function getQueryString(){

var url=location.href;

if(url.split('?')[1]!=undefined) {
var qs=url.split('?')[1];

String.prototype.splitQueryString=function() {
return this.split(/[=+&]/);
}

for(var c=1;c<qs.splitQueryString().length;c+=2) {
document.getElementById('inp'+c).value=qs.splitQueryString()[c];
}
}
}
window.addEventListener?
window.addEventListener('load',getQueryString,false):
window.attachEvent('onload',getQueryString);
</script>

</head>
<body>

<form action="">
<table><tr>
<td>Val A: </td><td><input type="text" id="inp1" name="A" readonly="readonly"></td>
</tr><tr>
<td>Val B: </td><td><input type="text" id="inp3" name="B" readonly="readonly"></td>
</tr></table>
</form>

</body>
</html>

birdbrain

Fotiman

7:13 pm on May 17, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You mention that one should never use document.write. Is this because the DOM cannot be updated?

document.write has some very serious time constraints. If it is run after the page finishes loading, it will totally wipe out your existing document. In addition, use of document.write encourages a coding style that mixes HTML markup and content with behavior (because you need to put scripts mixed in with your content where you want to write to occur) rather than promoting a good separation of layers (content / behavior / presentation). In general, it's better to use DOM methods or innerHTML to append or insert rather than use document.write.

However, as I said, if it's a POST request, you won't have access to that data at the JavaScript level.

SilverLining

8:19 pm on May 17, 2011 (gmt 0)

10+ Year Member



Thanks birdbrain. That's exactly what I need. I have a few questions for you:

  • Is there a particular reason why you increment "
    c
    " by 2 and not 1? [
    c+=2
    ]
  • I removed the "+" from
    [=+&]
    because I think "+" may be used for spaces. This doesn't seem to cater for spaces (+ or %20 in a url parameter). How can I add support for this?
  • First time I see
    Content-Style-Type
    meta tags. Will read up on this.

    Thanks again, Fotiman. I tried using jQuery .append and .html initially.

    I have read that one should be careful not to parse too many parameters in the query string, as different browsers may have different max values. Does anyone have more insight into this?
  • birdbrain

    9:13 pm on May 17, 2011 (gmt 0)



    Hi there SilverLining,

    when the query string...
    "a=aValue&b=bValue"

    ...is split we end up with this string....
    a,aValue,b,bValue

    This is zero based, and as we require items 1 and 3, then
    "c" must initially be set to 1 and then incremented by 2.

    I found in my tests that, the removal of the "+" from "[=+&]" would then
    allow spaces, the "+", and the "%20" to be used in the url parameter.

    birdbrain

    Fotiman

    11:32 pm on May 17, 2011 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



    If that's the desired outcome (using GET instead of POST), then I would change birdbrains example slightly:


    <!DOCTYPE html>
    <html>
    <head>
    <title>Test</title>
    </head>
    <body>
    <script>
    function getQueryString() {
    var qs = document.location.search,
    pairs,
    pair,
    key,
    value,
    el,
    i,
    n;
    if (qs.length > 0) {
    qs = qs.substr(1); // strip off the ?
    pairs = qs.split(/&/); // [foo=0, bar=1, ...]
    for (i = 0, n = pairs.length; i < n; i++) {
    pair = pairs[i].split(/=/); // [foo,0]
    key = pair[0];
    value = decodeURIComponent(pair[1].replace(/\+/g, " "));
    el = document.getElementById(key);
    if (el) {
    el.value = value;
    }
    }
    pairs = null;
    pair = null;
    el = null;
    }
    }
    window.addEventListener ? window.addEventListener('load',getQueryString,false) : window.attachEvent('onload',getQueryString);
    </script>
    <form method="get">
    <input id="foo" name="foo">
    <input id="bar" name="bar">
    <input id="baz" name="baz">
    <input type="submit" value="submit">
    </form>
    </body>
    </html>


    The main differences are:
    1. Uses location.search to get the query string
    2. Does not modify String.prototype (generally best to avoid modifying native objects)
    3. Splits the query string by & first, then splits each of the results by = (which I think is easier to follow for maintenance)
    4. Adds a check to see if the element exists before attempting to set the value
    5. Properly decodes the value

    SilverLining

    1:25 pm on May 19, 2011 (gmt 0)

    10+ Year Member



    Thanks birdbrain & Fotiman. That works great.

    Is there a catch to adding an email address to a hidden input form field? I also noticed that having an "@" symbol in the address bar causes the form to not submit. Does this need to be replaced?

    Fotiman

    3:04 pm on May 19, 2011 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



    @ gets encoded to %40
    If you submit a form containing an @ character (via GET), you will see it in the address bar as %40. You can verify this by using my example above. Just put in an email address in and submit. :)

    SilverLining

    7:50 am on May 24, 2011 (gmt 0)

    10+ Year Member



    Fotiman, you are right, however I'm using POST to post to a database.

    Fotiman

    12:48 pm on May 24, 2011 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



    Then as I already mentioned, you will not have access to the contents in the query string. So I'm not sure what it is that you think works in this case.

    SilverLining

    7:37 pm on May 24, 2011 (gmt 0)

    10+ Year Member



    The page is loaded from a URL which contains the data to pre-populate all form fields, so accessing the contents in the query string was only needed then, not on form submit.

    Fotiman

    10:00 pm on May 24, 2011 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



    Ok, then yeah, the link to that page would just need %40 in place of @. Sounds like you're all set. :)

    SilverLining

    7:21 am on May 25, 2011 (gmt 0)

    10+ Year Member



    All set, yes. Thank you for all the comments.