Search code examples
javascripthtmlformsurl-routing

Appending form value to action url - Dynamic


I've got a form like this:

<form action="http://localhost:8080/abc/def/gh" method="post">

I need to dynamically substitute localhost:8080 with the current hostname.

Something like using - window.location.hostname

For example, if the curent hostname on which the code is fired has address as 192.222.1.333:8080 then the code should dynamically turn to:

<form action="http://192.222.1.333:8080/abc/def/gh" method="post">

Solution

  • <html>
    <body>
        <form action="http://localhost:8080/abc/def/gh" id="action-form" method="post"></form>
    
        <script>
            var form = document.getElementById("action-form");
            form.action = form.action.replace("localhost:8080", window.location.hostname);
        </script>
    </body>
    </html>