0

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>
11
  • The rules of this coding challenge restrict me from using frameworks or libraries, (no jQuery) and no cookies, local or session storage. Commented Nov 3, 2022 at 15:52
  • What actual issue are you having? Commented Nov 3, 2022 at 16:06
  • I know how to display the form results on the same page. What I cannot figure out is how to send or pass the form results to a second page and then display the form results on the second page instead of the first page. Commented Nov 3, 2022 at 16:14
  • You can pass it as a query string from the URL, but you are required to use window.location for the purpose. Commented Nov 3, 2022 at 16:21
  • I'm not sure how to pass the values in a query string from the URL using window.location method. I am a noob at javascript and trying to learn it using vanilla javascript. Commented Nov 3, 2022 at 16:27

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

-1
const firstName = document.querySelector("#fName");
const lastName = document.querySelector("#lName");
const userName = document.querySelector("#user");
const phoneNumber = document.querySelector("#phoneNum");
const city = document.querySelector("#city");
const emailAddress = document.querySelector("#emailAdd");
const startingAmount = document.querySelector("#bankAmount");
const submitButton = document.querySelector("#submitBtn");

const firstNameFormat = /^[A-Za-z][A-Za-z~'\-\s]{0,33}[A-Za-z~'\-]?$/;
const lastNameFormat = /^[A-Za-z][A-Za-z~'\-\s]{0,43}[A-Za-z~'\-]?$/;
const userNameFormat = /^\d[A-Z]{3}[a-z][\$&*@!]$/;
const phoneNumberFormat = /^\d{3}\.\d{3}\.\d{4}$/;
const cityFormat = /^[A-Za-z]{1,50}$/;
const emailAddressFormat = /^[\w.-]+@[a-zA-Z0-9-]+\.(com|ca)$/;
const startingAmountFormat = /^(?:[68]|[1-9]\d*[02468]|5000)$/;
const MONTHARR = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

const fields = [firstName, lastName, userName, phoneNumber, city, emailAddress, startingAmount];
const formats = [firstNameFormat, lastNameFormat, userNameFormat, phoneNumberFormat, cityFormat, emailAddressFormat, startingAmountFormat];
const fieldNames = ["firstName", "lastName", "userName", "phoneNumber", "city", "emailAddress", "startingAmount"];

const ELEMENTS = fields.map((field, index) => ({
    name: fieldNames[index],
    field: field,
    format: formats[index]
}));

// ------------- VALIDATION -------------
function validate(format, field) {
    if (format.test(field.value)) {
        field.style.backgroundColor = "#fff";
        displayErrorMessage(field, false);
    } else {
        field.style.backgroundColor = "#f9c7c7";
        displayErrorMessage(field, true);
    }//if
}//validate()

function displayErrorMessage(field, valid) {
    switch (field) {
        case firstName:
            document.querySelector("#errFName").innerText = valid ? "First name: Max 35 characters, must start with a letter, and can only contain letters, space, ~, ' and -." : '';
            break;
        case lastName:
            document.querySelector("#errLName").innerText = valid ? "Last name: Max 45 characters, must start with a letter, and can only contain letters, space, ~, ' and -." : '';
            break;
        case userName:
            document.querySelector("#errUserName").innerText = valid ? "Username must start with a number, followed by three uppercase letters, a lowercase letter, and end with $, &, *, @, or !." : '';
            break;
        case phoneNumber:
            document.querySelector("#errPhoneNum").innerText = valid ? "Phone number format: ###.###.####" : '';
            break;
        case city:
            document.querySelector("#errCity").innerText = valid ? "City name must contain only letters and have a max of 50 characters." : '';
            break;
        case emailAddress:
            document.querySelector("#errEmail").innerText = valid ? "Email format: [email protected] or [email protected]." : '';
            break;
        case startingAmount:
            document.querySelector("#errStartingAmount").innerText = valid ? "Amount must be between $5 and $5000, divisible by 2, and have no decimals." : '';
            break;
    }//switch
}//displayErrorMessage

function changeInvalidFields() {
    for (let i = 0; i < fields.length; i++) {
        validate(formats[i], fields[i]);
    }
} //changeInvalidFields

function validateForm() {
    let isValid = true;
    for (let i = 0; i < fields.length; i++) {
        if (!formats[i].test(fields[i].value))
            isValid = false;
    } //for

    return isValid;
}//validateForm()


ELEMENTS.forEach(el => {
    el.field.addEventListener('blur', function () { validate(el.format, el.field); }, false);
});
submitButton.addEventListener('click', function () { changeInvalidFields(); }, false);

// ---------STORING VALUES IN LOCAL STORAGE------------

let now = new Date();
let month = MONTHARR[now.getMonth()];
let day = now.getDate();
let year = now.getFullYear();
let hour = now.getHours();
let min = now.getMinutes();
let currentVisit = `${month} ${day}, ${year} at ${hour < 13 ? hour : hour - 12}:${min < 10 ? "0" + min : min} ${hour < 12 ? "AM" : "PM"}`;


function setLocalStorage() {
    localStorage.setItem("currentVisit", currentVisit);
    localStorage.setItem("lastVisit", currentVisit);

    ELEMENTS.forEach(el => {
        if (el.field.value.length > 0) {
            localStorage.setItem(el.name, el.field.value);
        }
    })
}

function checkKeys(f) {
    let stop = false;
    let key;
    for (let x = 0; x < localStorage.length && stop === false; x++) {
        key = localStorage.key(x);
        if (key === f)
            return true;
    }
    return false;
}

function checkLocalStorage() {
    if (localStorage.length > 0) {
        if (fieldNames.every(checkKeys)) { // checks every key exists in localStorage 
            localStorage.setItem('lastVisit', localStorage.getItem('currentVisit'));
            localStorage.setItem('currentVisit', currentVisit);
            return true;
        } else{
            localStorage.setItem('firstVisit', true);
            return false;
        }
    } else{
        localStorage.setItem('firstVisit', true);
        return false;
    }
}

if (checkLocalStorage()){
    console.log("returning user");
    location.href = "game.html"; // redirects directly to game if user already exists in localStorage

}else{
    console.log("first time");
}


document.querySelector("#formLayout").onsubmit = function(event){
    if(validateForm()){
        setLocalStorage();
        return true;
    }else{
        return false;
    }
}
// document.querySelector("#formLayout").onsubmit = validateForm;




let queryString = window.location.search;
let values = [];


queryString = queryString.substring(1);

while(queryString.indexOf("+") !== -1)
    queryString = queryString.replace("+", " ");

let qArray = queryString.split("&");

for(let i = 0; i < qArray.length; i++){
    let pos = qArray[i].search("=");
    let keyVal = qArray[i].substring(0, pos);
    let dataVal = qArray[i].substring(pos + 1);
    dataVal = decodeURIComponent(dataVal);
    values[keyVal] = dataVal;
}//for

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.