Issues with session storage for multiple forms

I have 2 separate forms that displays in one iframe, I want users to enter data in the input, click on next button then enter input of form 2, click on a review button, then show form 1 and form 2 output in one preview page before submitting the data to a database. I have tried session storage but I know that my code is wrong.

Problem is that form 1 input doesnt show on the preview, only form 2 input shows.

var formValues = [];
SessionStorage.setItem("fname", "fname");
SessionStorage.setItem("lname", "lname");
SessionStorage.setItem("phone-field", "phone-field");
SessionStorage.setItem("email-field", "email-field");

$(document).ready(function() {
  $(".next").click(fuction() {
    $("#fname").val("fname");
    $("#lname").val("lname");
    $("#phone-field").val("phone-field");
    $("#email-field").val("email-field");


var formValues = sessionStorage.getItem("fname");
console.log(formValues);

$(document).ready(function() {

                $('.next').click(function() {
                  var formValues = [];
                  // get values from inputs in first fieldset
                  $('.field1 :input').each(function() {
                    formValues.push($(this).val());
                  });

                  formValues.pop(); //remove the button from input values
                  console.log(formValues);

                // set values in second fieldset
                  $('.field3 :input').each(function(index) {
                    if (formValues[index]) {
                      $(this).val(formValues[index]);
                    }
                  });

                  $('.current').removeClass('current').hide().next().show().addClass('current');

                });

                $('.previous').click(function() {
                  $('.current').removeClass('current').hide().prev().show().addClass('current');

                });
              });   

                   $(document).ready(function() {

                $('.review').click(function() {
                  var formValues = [];
                  // get values from inputs in first fieldset
                  $('.field2 :input').each(function() {
                    formValues.push($(this).val());
                  });

                  formValues.pop(); //remove the button from input values
                  console.log(formValues);

                  // set values in second fieldset
                  $('.field3 :input').each(function(index) {
                    if (formValues[index]) {
                      $(this).val(formValues[index]);
                    }
                  });

                  $('.current').removeClass('current').hide().next().show().addClass('current');

                });

                $('.previous').click(function() {
                  $('.current').removeClass('current').hide().prev().show().addClass('current');

                });
              });   

FORM 1

<head>
  <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
  <script data-require="bootstrap@4.0.5" data-semver="4.0.5" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
  <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <form id="helpdeskform" action="process.php" method="post">
    <fieldset class="field1 current">
      <h2>Form</h2>
      <p>
        <label class="form-label first-name" for="fname">First Name:</label>
        <input name="fname" id="fname" placeholder="First Name" type="text" />
      </p>
      <p>
        <label class="form-label last-name" for="lname">Last Name:</label>
        <input name="lname" id="lname" placeholder="Last Name" type="text" />
      </p>
      <p>
        <label class="form-label" for="phone-field">Phone:</label>
        <input name="phone" id="phone-field" placeholder="Phone Number" type="text" />
      </p>
      <p>
        <label class="form-label" for="email-field">E-mail:</label>
        <input name="email" id="email-field" placeholder="E-mail" type="text" />
      </p>
      <hr />
      <label for="review">
        <input onclick="location.href='index3.html'" id="next" name="next" class="next action-button" value="Next" type="button" />
      </label>
    </fieldset>
    <fieldset class="field3">

      <p>First Name:
        <input class="show_fname" readonly="readonly" type="text" />
      </p>
      <p>Last Name:
        <input class="show_lname" readonly="readonly" type="text" />
      </p>
      <p>Type of Request:
        <input class="show_type_of_request" readonly="readonly" type="text" />
      </p>
      <p>Short Description:
        <input class="show_subject" readonly="readonly" type="text" />
      </p>
      <p>Additional Comments:
        <input class="show_comments" readonly="readonly" type="text" />
      </p>
      <p style="float:left;">
        <label for="previous">
          <input name="previous" class="previous action-button" value="Previous" type="button" />
        </label>
      </p>
      <p style="float:left; padding-left: 10px;">
        <label for="Submit">
          <input value="Submit" name="submit" class="action-button" type="submit" />
        </label>
      </p>
    </fieldset>
  </form>
</body>

</html>

FORM 2

<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
  <script data-require="bootstrap@4.0.5" data-semver="4.0.5" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
  <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <form id="helpdeskform" action="process.php" method="post">
    <fieldset class="field2 current">
      <h2>Form 2</h2>
      <label for="classify">Type of Request:</label>
      <select name="classify" id="classify">
        <option value="">Please select an option..</option>
        <option value="maintainence">Maintainence of Site</option>
        <option value="troubleshoot">Troubleshoot/Error</option>
        <option value="new">Create new content</option>
      </select>
      <p></p>
      <p>
        <label for="subject">Short Description: <span class="counter-field">
              <span id="counter"></span> characters left.</span>
        </label>
        <input name="subject" id="subject" placeholder="Subject" type="text" />
      </p>
      <p>
        <label for="desc">Additional Comments:</label>
        <textarea style="font-family: Arial, Veranda, Sans serif" name="desc" id="desc" cols="30" rows="10" placeholder="Short Description"></textarea>
      </p>
      <p>
        <label for="review">
          <input name="review" onclick="showData();" class="review action-button" value="Review" type="button" />
        </label>
      </p>
    </fieldset>
    <fieldset class="field3">
      <!-- @TODO PREVIEW ALL FORM INPUTS -->
      <p>First Name:
        <input class="show_fname" readonly="readonly" type="text" />
      </p>
      <p>Last Name:
        <input class="show_lname" readonly="readonly" type="text" />
      </p>
      <p>Phone:
        <input class="show_phone" readonly="readonly" type="text" />
      </p>
      <p>E-mail:
        <input class="show_email" readonly="readonly" type="text" />
      </p>
      <p>Type of Request:
        <input class="show_type_of_request" readonly="readonly" type="text" />
      </p>
      <p>Short Description:
        <input class="show_subject" readonly="readonly" type="text" />
      </p>
      <p>Additional Comments:
        <input class="show_comments" readonly="readonly" type="text" />
      </p>
      <p style="float:left;">
        <label for="previous">
          <input name="previous" class="previous action-button" value="Previous" type="button" />
        </label>
      </p>
      <p style="float:left; padding-left: 10px;">
        <label for="Submit">
          <input value="Submit" name="submit" class="action-button" type="submit" />
        </label>
      </p>
    </fieldset>
  </form>
</body>

</html>


Hi @mixirocking, I don’t see where you are storing any form values to the session storage (or trying to access them)… but if the two forms are on the same page, you don’t need that anyway. Just declare the formValues variable in a common scope, for example at the top of $(document).ready():

$(document).ready(function () {
  var formValues = []

  $('.next').click(/* ... */)
  $('.previous').click(/* ... */)
  $('.preview').click(/* ... */)
})

BTW, you have 2 document ready listeners inside a click listener inside another document ready listener… that can’t be right. Just attach all your element event listeners inside a single document ready listener.

PS: If you’re just .hide()ing the 1st form and .show()ing the 2nd, why store the values in a variable in the first place? You can just evaluate both forms when the user reaches the preview-part. The form values won’t disappear when the forms are not visible. :-)

Hi m3g4p0p, I have 3 pages, index2.html is form1, index3.html is form2 and then I have index.html has an iframe and 2 hyperlinks called form 1 and form 2, user clicks on form1 hyperlink, then the form 1(index2.html) opens in the iframe, user enter data in form fields, then click on next, the second form opens and user enters values, then click on review button to review all form inputs. I’m not sure how to add values into a session and the retrieving the values, I have read about sessionStorage.getItem(key) and sessionStorage.setItem(key,value) but my execution of the code isn’t working.

Ah sorry I hadn’t looked at your markup properly… so there are submit buttons in the iframes. Is the user supposed to submit the form, or click that next button on the parent page? Because after the form got submitted, the values are gone; you’d have to intercept the form submission first. But then again, a preview wouldn’t make much sense when the form already got submitted anyway.

And is that script supposed to run on the parent page? Then you’d have to access the values within the iframes with .contents() (or via window.frames with vanilla JS). If it’s running in the iframes, you’ll have to access the parent first, and access the other iframe from there.

But why are you using iframes in the first place? A multistep form would be much easier to implement if you just show/hide the current form step on the same page, without all the hassle of communicating between the iframes…

The index.html is the parent page with the iframe, I used <a href="index2.html" target="preview-iframe">Form 1</a> to target the form pages to the iframe. Form 1 only has one button: next (in the iframe), I want to use the next button to store a sessionsStorage/localStorage of the values and go to the next form (if its possible), form 2 has one button: review, the review will go <fieldset class="field3"> preview all inputs of both forms. The review page has submit and previous buttons.

I’m using iframes because my boss said he wants iframes.

Preview of code

The preview code doesn’t have sessionStorage yet.

1 Like

Thx for the plunkr, I think I get it now – also, your JS is much cleaner there. :-) I think here’s the error:

// Event listener for when the bookings form is submitted.
form.addEventListener(".save", function(e) {
  saveData(form);
});

That’s not how .addEventListener() works – you call it on the event target, and the first paramter is the event type. Also, you’ll have to call e.preventDefault(), because otherwise the form will just get submitted and all JS operations will get aborted:

var saveButton = form.querySelector('.save')

saveButton.addEventListener('click', function (e) {
  e.preventDefault()
  saveData()
})

And then you have that part in an .onload function, but you are re-assigning that value at the bottom with another .onload function. To avoid this, use .addEventListener() for that event as well:

window.addEventListener('load', function () {
  // ...
})

And finally, there’s a typo here:

var fname = document.getElementById("fran_name"); // should be "fname"

BTW, you don’t need to include that script in the parent page then; and in the iframes, I’d either write separate scripts, or formulate the storing of the form values in a more generic way (e.g. by iterating over all input elements instead of using IDs).

But still, if you must use an iframe, couldn’t you have all that form functionality on one single page, rather than changing the location of the iframe?

1 Like

PS: Here’s one (basic) approach; note that you can only store strings to the localStorage, so we have to use JSON.parse() / JSON.stringify():

const formData = JSON.parse(localStorage.formData || '{}')
const inputEls = document.querySelectorAll('input')
const form = document.querySelector('form')

// Populate stored data
inputEls.forEach(el => {
  const value = formData[el.name]

  if (value !== undefined) {
    el.value = value
  }
})

// Store form data on submit
form.addEventListener('submit', evt => {
  evt.preventDefault()

  inputEls.forEach(el => {
    formData[el.name] = el.value
  })

  localStorage.formData = JSON.stringify(formData)
})
1 Like

Ahh okay, thank your for the examples and help, the reason that the forms are on different html pages is because the real code that I’m coding have a lot more forms that is much longer. :joy:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.