Kev
Kev

Reputation: 31

Populating a HTML input field from a hyperlink?

I’m not sure if this is possible (hence me posting here). I’ve not been able to find any documentation on this anywhere, so I either can’t be done, or I’m an idiot and have missed something super obvious.

So it’s possible to populate the subject line of an email with a mailto link like this:

<a href="mailto:[email protected]?subject=Testing out mailto!">First Example</a>

I have a button on my website that displays under all blog posts. This button goes to my guestbook (yes, guestbooks still exist). What I’d like is to have a field on my guestbook signing form to be auto populated with the link they came from. So I know the referring link.

So, for example, if someone is reading https://example.com/post-1

When they click the “sign my guestbook” button it would automatically populate the “Post you’re responding to” HTML input field with https://example.com/post-1

Is this possible in plain old HTML? If not, what would be the best way to achieve this aim?

Thanks in advance!

Upvotes: 2

Views: 421

Answers (1)

Rounin
Rounin

Reputation: 29453

Essentially, a single line of javascript is all you need:

document.getElementById('myInput').value = document.referrer;

This is because:

document.referrer

tells you the URL of the page you visited which linked to the page you are visiting now.


Working Example:

const referringPostInput = document.getElementById('referring-post');
referringPostInput.value = document.referrer;
referringPostInput.size = referringPostInput.value.length;
<form>
<fieldset>
<legend>Post you're responding to:</legend>
<input type="url" name="referring-post" id="referring-post" readonly />
</fieldset>
</form>

Upvotes: 1

Related Questions