Pre-fill form field via URL in html

前端 未结 4 2201
一向
一向 2020-12-06 01:40

I am looking for a simple way to pre-fill a field in my contact form when ever a user clicks on a link that is given in some other page.

This is my contact form in h

4条回答
  •  自闭症患者
    2020-12-06 02:30

    A more modern way would be to use the URL() constructor and the searchParams property. Let the browser engine do the work!

    (new URL(window.location.href)).searchParams.forEach((x, y) =>
        document.getElementById(y).value = x)
    

    Try it online! or on Stack Overflow:

    const hash = '?name=some_text&email=more%20text';
    const example = "http://example.com/" + hash;
    
    (new URL(example)).searchParams.forEach((x, y) =>
        document.getElementById(y).value = x);

    Your name:

    Your email:

提交回复
热议问题