Picking a Random Item from an Array

The code below is for a multiple page form.
As you can see it adds a whole lot more complexity and time to it.

You will need to:

  • first page: add document.addEventListener('DOMContentLoaded', firstPageLoad)

  • All other pages add document.addEventListener('DOMContentLoaded', pageLoad) inline <script>

  • Put the rest of the functions in an index.js file and link in every page <script src = 'index.js'><script> in the <head>

  • On the first page DO NOT have a back button

  • On the last page DO NOT have a next button (put your submit button)

  • On every page you will need to have this variable inline let thisPage = 'pageOne'; except change it to whatever page it is.

  • Change the window.location.href = http://127.0.0.1:5500/${formPages[pos]}; to whatever url you are using

  • Change the window.location.href = '' to whatever the url of final (after form finished) page

JS code:

   let thisPage = 'formPage1.html';

Array.prototype.shuffle = function () {
  let input = this;
  for (let i = input.length - 1; i >= 0; i--) {
    let randomIndex = Math.floor(Math.random() * (i + 1));
    let itemAtIndex = input[randomIndex];
    input[randomIndex] = input[i];
    input[i] = itemAtIndex;
  }
  return input;
}

firstPageLoad = function(){
// check for local Storage
if(!localStorage) return alert('Please change privacy settings to allow local storage and reload');

// check to see if page has been visited before 
let isVisited = localStorage.getItem('visited');
console.log(`isVisited :${isVisited}`);
if(isVisited !== null) return getPageData();

// shuffle the page orders
var firstPages = ['formPage1.html'];
var randoms = ['formPage2.html','formPage3.html','formPage4.html' ];
var lastPages = ['formPage5.html'];
randoms.shuffle();
let pages = firstPages.concat(randoms, lastPages);


//set routes/ positions/ visited pages in local storage

localStorage.setItem('pageArray',JSON.stringify(pages)); 
localStorage.setItem('pos', 0);
 
}

const pageLoad = function(){
   // check to see if page has been visited before and if so get page data
    let getVisited = localStorage.getItem('visited');
    let isVisited = JSON.parse(getVisited);
    if(isVisited.includes(thisPage)) return getPageData(); 
}


// adds previous data to the page if it has been visited
const getPageData = function(){
    let getPage =  localStorage.getItem(thisPage); 
    let pageData = JSON.parse(getPage);
    for(let[key, value] of Object.entries(pageData))
    {let node = document.querySelector(`[name ~= ${key}]`);
    node.value = value;
    }
}

const changePage = function (direction) { 
    // set the currentPage as having been visited
    let getVisited = localStorage.getItem('visited');
    let isVisited = [];
    if (getVisited !== null) isVisited = JSON.parse(getVisited)
    isVisited.push(thisPage);
    localStorage.setItem('visited', JSON.stringify(isVisited));

    // create page data object
    let pageData = {};

    // get all inputs and set page data object to input values
    let inputs = document.querySelectorAll('input');
    for(let i of inputs){pageData[i.name] = i.value}

    // put pageData into local storage
    localStorage.setItem(thisPage, JSON.stringify(pageData));
    
    // check to see what our position/ route is
    let position = localStorage.getItem('pos');
    let getPages = localStorage.getItem('pageArray');
    let formPages = JSON.parse(getPages);
     
    // navigate to next page and change our position
    direction === 'forward' ? localStorage.setItem('pos', (parseInt(position) +1)) : localStorage.setItem('pos', (parseInt(position) -1));
    let pos = localStorage.getItem('pos');
   window.location.href = `http://127.0.0.1:5500/${formPages[pos]}`;

}

const submitForm = function(){
    // create page data object
    let pageData = {};

    // get all inputs and set page data object to input values
    let inputs = document.querySelectorAll('input');
    for(let i of inputs){pageData[i.name] = i.value}

    // put pageData into local storage
    localStorage.setItem(thisPage, JSON.stringify(pageData));


    // create a form data obj
    var formData = new FormData();

    // get the pages in order
    let getPages = localStorage.getItem('pageArray');
    let formPages = JSON.parse(getPages);

    // loop through every page and get page objects
    for(let i of formPages){
        var getPage = localStorage.getItem(i);
        var p = JSON.parse(getPage);

        // loop through every key value and insert into myForms
        for(let[key, value] of Object.entries(p))
        { formData.set(key, value)}

    
    }
    

for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); }

    // clear the local storage
    localStorage.clear();

    // post the form data
    let form = document.querySelector('form');
    fetch(form.action, {method:'post', body: formData});

    // navigate away from the form
    window.location.href = '';
}


const forwardButton = () => {changePage('forward')}
const backButton = () => {changePage('back')}

document.addEventListener('DOMContentLoaded', firstPageLoad);

I have given this a test.
This will get you 95% of the way to what you want to achieve.
You will need to implement the rest and test it.

If you have any errors that you cant work out, jump back on the forum. It also helps if you understand on a basic level how this stuff is working. I have left comments in the code.

When you post back on the forum it also helps if you can post whatever the error code is.

Also @kirupa @senocular and @krilnon have way more experience and can probably give you better tips than I can.
Best of luck :slightly_smiling_face:

Hey ! hows it going, I ended up stumbling upon this page and your post has been so much help for my hw! But I was wondering if you could help me out… Is it possible to ask a user to input how many random items to select from an array? For example give him a prompt where he ends up answering 5 , so we then output 5 random items from the array?

Welcome! :grinning:

The easiest way would be to shuffle your array first. That will ensure each item in your array is probably different than what you had originally prior to shuffling: Picking a Random Item from an Array - #11 by kirupa

From there you can just pick the first 3 or 5 or whatever number of items the user specified.

Does that help?

:partying_face: