tmparisi
tmparisi

Reputation: 111

Any way to autopopulate HTML form textbox with data in URL string?

Is it possible to autopopulate a textbox on a page depending on a string passed in with the URL. For example:

Say we have the following form:

<form name="form_reservation" id="form-reservation">
                    <div style="padding:10px 20px 10px 10px;">
                    <label for="reservation-id">Reservation ID</label>
                        <input name="reservation_id" id="reservation-id" class="reservationid" style="width:120px !important"/>
                        <div style="padding:5px 20px 0px 10px;" class="res_message" id="res-message">&nbsp;</div>
                        <input type="submit" class="button" value="Search Reservation" name="search_button" style="width:150px !important; margin:10px 0px 0px 5px;"/>
                        <input type="button" class="button" value="Clear" style="width:150px !important; margin:10px 0px 0px 5px;" onclick="resetForms('reservation')" />
                    </div>
                </form>

And the user received an email with a link in it: www.website.com/formpage.html######

Where ###### was the ID that I wanted to populate in the reservation-id field on the form. Any way to make this happen?

Upvotes: 1

Views: 2689

Answers (2)

Banjer
Banjer

Reputation: 8300

Assuming the URL the user clicks looks like www.website.com/formpage.html?id=12345, you can spit it out into the input "value" field with GET, e.g.:

<input value="<?php echo htmlspecialchars($_GET["id"]); ?>" name="reservation_id" id="reservation-id" class="reservationid" style="width:120px !important" />

This is the way to do it with php.

EDIT:

Per @Esailija's comment, I wrapped it in the htmlspecialchars function, which as far as I understand will help safeguard against XSS attacks.

Upvotes: 1

Mihai Iorga
Mihai Iorga

Reputation: 39704

Javascript:

<script>
    var hash = window.location.hash.replace('#', ''); // get hash and replace the '#' (hash) tag
    document.getElementById('reservation-id').value = hash; // add value to input
</script>

I assumed you were talking about hash location url.html#1111, this can be accomplished only in JavaScript.

Upvotes: 0

Related Questions