javascript

Pass form values in querystring to another page using vanilla javascript


I am trying to pass the values from form inputs to another page using vanilla javascript. I'm using URLSearchParams and querystrings to get the values and can successfully display them on the same page. What I cannot figure out is how to send the form values to another page and display them on that page. I have created a pen with the form here: https://codepen.io/JapperCat/pen/ExRKJyV

<form action="./page2.html" id="sample-form">
  <label for="fullname">Full Name</label>
  <input type="text" name="fullname">

  <br><br>

  <label for="age">Age</label>
  <input type="text" name="age">

  <br><br>

  <label for="gender">Gender</label>
  <select name="gender" id="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
  </select>

  <br><br>

  <label for="email">Email</label>
  <input type="email" name="email" id="email">

  <br><br>

  <label for="mytoys">My Toys</label>

  <br>

  <input type="checkbox" id="mytoys" name="mytoys" value="Bike">
  <label for="bike"> I have a bike</label><br>

  <input type="checkbox" id="mytoys" name="mytoys" value="Car">
  <label for="car"> I have a car</label><br>

  <input type="checkbox" id="mytoys" name="mytoys" value="Boat">
  <label for="boat"> I have a boat</label><br><br>

  <input type="submit">
</form>

<p id="showFullname"></p>
<p id="showAge"></p>
<p id="showGender"></p>
<p id="showEmail"></p>
<p id="favToy"></p>

<script>
  const form = document.getElementById("sample-form");
  form.addEventListener("submit", (evt) => {
    evt.preventDefault();
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    // Convert to raw query string
    console.log(params.toString());
    // Loop over each key-value pairs using array destructuring
    for (const [key, value] of params) {
      console.log(`${key} => ${value}`);

      // Output result of inputs
      const fullname = params.get("fullname");
      const age = params.get("age");
      const gender = params.get("gender");
      const email = params.get("email");
      const mytoys = params.get("mytoys");
      // Display values on screen
      document.getElementById("showFullname").innerHTML = `Your full name is: ${fullname}`;
      document.getElementById("showAge").innerHTML = `Your age is: ${age}`;
      document.getElementById("showGender").innerHTML = `Your gender is: ${gender}`;
      document.getElementById("showEmail").innerHTML = `Your email is: ${email}`;
      document.getElementById("favToy").innerHTML = `Your favorite toy is: ${mytoys}`;
    }
  });
</script>

Solution

  • First of all your checkboxes are invalid because they all have the same id every element needs to have a unique id. Also, since they appear to belong in an array together (same name) the name should have brackets [] after it i.e name="mytoys[]".
    After building your query string, all you have to do is concatenate it with the URL of the page you whish to send it to (I'm assuming you want to send it to the URL in the form.action)

    const GetURL = `${form.action}?${params.toString()}`;
    

    Then to send a GET Request use window.location(GetURL).

    In my snippet I've added a confirm() popup to show the URL before sending the Request. It will look something like this: https://stacksnippets.net/page2.html?fullname=dude&age=9&gender=Male&email=dude%40mail.com&mytoys%5B%5D=Bike&mytoys%5B%5D=Boat The stacksnippets.net/ part is there because the action is a relative URL, and will have the domain of wherever it is running.

    const form = document.getElementById("sample-form");
    form.addEventListener("submit", (evt) => {
      evt.preventDefault();
      const formData = new FormData(form);
      const params = new URLSearchParams(formData);
      // Convert to raw query string
      const GetURL = `${form.action}?${params.toString()}`;
      console.log(GetURL);
      if (confirm(`Submitting GET Request to: ${GetURL}`)) {
        // confirm is for demo, you only need this next line
        window.location = GetURL;
      }
    });
    <form action="./page2.html" id="sample-form">
      <label for="fullname">Full Name</label>
      <input type="text" name="fullname">
      <br><br>
      <label for="age">Age</label>
      <input type="text" name="age">
      <br><br>
      <label for="gender">Gender</label>
      <select name="gender" id="gender">
        <option value="Male">Male</option>
        <option value="Female">Female</option>
        <option value="Other">Other</option>
      </select>
      <br><br>
      <label for="email">Email</label>
      <input type="email" name="email" id="email">
      <br><br>
      <label for="mytoys[]">My Toys</label>
      <br>
      <input type="checkbox" id="mytoys_bike" name="mytoys[]" value="Bike">
      <label for="bike"> I have a bike</label><br>
    
      <input type="checkbox" id="mytoys_car" name="mytoys[]" value="Car">
      <label for="car"> I have a car</label><br>
    
      <input type="checkbox" id="mytoys_boat" name="mytoys[]" value="Boat">
      <label for="boat"> I have a boat</label><br><br>
    
      <input type="submit">
    </form>

    Your page2.html will look something like the following snippet.
    Note, I had to use some dummy data to replicate the value of window.location.search as this will not work in the snippet.

    const dummy = 'fullname=dude&age=9&gender=Male&email=dude%40mail.com&mytoys%5B%5D=Bike&mytoys%5B%5D=Boat'
    const fields = ['fullname', 'age', 'gender', 'email', 'mytoys[]']
    const results = document.querySelector('#results');
    const queryString = window.location.search;
    // won't work in fiddle/snippet
    //const urlParams = new URLSearchParams(queryString);
    // using dummy string here
    const urlParams = new URLSearchParams(dummy);
    
    fields.forEach((param) => {
      console.log(urlParams.getAll(param))
      const dispVal = urlParams.getAll(param).join(', ')
      results.append(`${param}: ${dispVal}`)
      results.append(document.createElement('br'))
    })
    <div id="results"></div>

    page2 fiddle