Search code examples
javascriptformspostgethidden

How to change the value when I type ?variable=value at url?


Situation:

  1. The input value is empty and the type is hidden.
  2. I type ?hiddenname=007 at url
  3. I click the button"submit" and cause function call()..

Expect:

  1. The system fills in the value into the input according to ?hiddenname=007 at url using function call()
  2. after that, the system send the form with value 007 to the server.

Current result:

  1. the system still send the form with empty value.

url

localhost/index.html?hiddenname=007

index.html

<!DOCTYPE html>
<html>
    <head>
        <script>
            function call(){
                document.forms["form1"].hiddenname.value=hiddenname;
                    console.log("function run");
                    }
        </script>
    </head>
    <body>
        <form name="form1" action="end.php">
            <input type="hidden" id="hiddenid" name="hiddenname" value="" />
              <input type="submit" id="send" onclick="call()"/>
            
        </form>
    </body>

end.php

<?php
echo $_GET['hiddenname'];
?>

Solution

  • This will obtain on window load the value of hiddenname from the URL query string, then set the value of the hiddenid input:

    window.onload = function () {
    
      // get the search params from the window's URL
      const urlParams = new URLSearchParams(window.location.search);
    
      // get the value of 'hiddenname'
      const myParam = urlParams.get('hiddenname');
    
      // store this value in the input with id="hiddenid"
      document.getElementById('hiddenid').value = myParam;
    };