1

I'm trying to validate my form, but I can't seem to capture my form values! At a loss as to where to go now. I've tried a combination of jQuery and Javascript. Here's a snippet of my code.

HTML:

<form action="#" name="application-form" method="post" enctype="multipart/form-data">
          <ul>
            <li class="input-row">
              <label for="app-resume">Resume</label>
              <input type="file" id="app-resume" name="resume" />
            </li>
            <li class="input-row">
              <label for="app-name">Full Name</label>
              <input type="text" id="app-name" name="fname" />
            </li>
            <li class="input-row">
              <label for="app-pnum">Phone Number</label>
              <input type="number" id="app-pnum" name="pnum" />
            </li>
            <li class="input-row">
              <label for="app-email">Email</label>
              <input type="email" id="app-email" name="email" />
            </li>
            <li class="input-row">
              <label for="app-info">Additional Information</label>
              <textarea type="text" id="app-info" name="info"></textarea>
            </li>
          </ul>
          <div class="btn-mssg-container">
            <button type="submit" name="sbt-btn" id="sbt-btn">apply</button>
            <p id="sbt-mssg" class="hidden">Thank you for applying.</p>
          </div>
        </form>

JS:

var myForm = document.forms["application-form"];
myForm.onsubmit = processForm;
function processForm(){
  console.log(myForm.fname.value); 
}

I've also tried:

function processForm(){
  var inName = $("#app-name").val();
  console.log(inName);
}

I'm getting nothing! Someone please put me out of my misery.

9
  • 1
    Check console for any error. Your example using the second way works fine in codepen. Commented Dec 31, 2017 at 22:44
  • The first example seems to work fine as well. It logs what you type in the fname field. Commented Dec 31, 2017 at 22:48
  • No errors in my console - I've checked the typeof value returned and it's a string, but always empty. Commented Dec 31, 2017 at 23:04
  • I suppose that pressing "apply" triggers a page reload. Commented Dec 31, 2017 at 23:06
  • @leaf - i'm an idiot. Thank you for mentioning this. I've just been resetting my input variables to blank. Commented Dec 31, 2017 at 23:08

1 Answer 1

1

The first attempt at getting form values is called HTMLFormControlsCollection


1. Reference the form:

var FoRm = document.forms.FormID_or_NAME

OR

var FoRm = document.forms["FormID_or_NAME"]

OR

var FoRm = document.forms[0]

The last one using index number zero in bracket notation will work if the target <form> is the first on the page or the only <form> on the page.


2. Collect all of the form's form controls into an array-like object:

var formControlS = FoRm.elements

Step 2. was the crucial step that you were missing.


3. Now you can reference and get values from any form control under that specific <form>:

var foRmC = formControlS.FormControlID_or_NAME.value

OR

var foRmC = formControlS["FormControlID_or_NAME"].value

OR

var foRmC = formControlS[0].value


Details are commented in Demo

This localStorage feature cannot work in a Stack Snippet due to security measures. If you want to review a fully functional demo, then visit Plunk

Demo

<!DOCTYPE html>
<html>

<head>
  <style>
    #main {
      display: flex;
      justify-content: space-around;
      flex-wrap: nowrap;
    }
    
    iframe {
      display: inline-table;
      max-width: 40%;
      height: 100vh
    }
    
    #app0 {
      max-width: 60%;
      margin: 0 0 5px 15px;
    }
    
    label {
      display: inline-block
    }
    /* Area code - Central Office code */
    
    [type=number] {
      width: 5ch
    }
    /* The last 4 digits - Station code */
    
    label [type=number]:last-of-type {
      width: 6ch
    }
    
    [type=email] {
      width: 26ch
    }
    
    .hidden {
      opacity: 0
    }
    
    #msg {
      height: 60px;
      overflow-x: hidden;
      overflow-y: scroll;
      border: 3px inset grey;
      padding: 10px;
      display: block;
    }
  </style>
</head>

<body>
  <main id='main'>
    <!-- On submit, form sends to a real test server
    || The target attribute value is the name of 
    || iframe#display. Whenver data is tested thru 
    || this server, it will send a response later. 
    -->
    <form action="https://httpbin.org/post" id="app0" method="post" enctype="multipart/form-data" target='display'>

      <fieldset id='set0'>

        <label for="file0">Resume</label>
        <input type="file" id="file0" name="resume">
        <br>
        <br>

        <label for="name0">Full Name</label>
        <input type="text" id="name0" name="name">
        <br>
        <br>

        <label>Phone Number
          <input type="number" id="area0" name="phone" min='100' max='999'>
          <input type="number" id="cent0" name="phone" min='100' max='999'>
          <input type="number" id="stat0" name="phone" min='0000' max='9999'>
        </label>
        <br>
        <br>

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

        <label for="info0">Additional Information</label>
        <br>
        <textarea id="info0" name="info" cols='28'></textarea>
        <br>

      </fieldset>

      <fieldset id="set1">
        <button id='btn' type="button" class=''>Process</button>
        <button id='sub' type='submit' class='hidden'>Transfer</button>

      </fieldset>
      <output id="msg"></output>
    </form>

    <iframe name='display' src='about:blank' width='60%'></iframe>

  </main>
  <script>
    /* The interface used to refer to form controls
        || is called HTMLFormControlsCollection
        */ // Reference the form
    var xApp = document.forms.app0;

    /*\\\\\\\\\\/IMPORTANT\//////////
    This is the part that was in error
    In order to refer to any form controls
    of the referenced form, you must
    collect them in an array-like object
    using the .elements proerty //////*/

    var xCon = xApp.elements;

    // Then from the .elements reference by id
    // A click event on a button--processForm
    // is called
    xCon.btn.onclick = processForm;

    /* This function will gather all form values
    || into an array.
    || Then it stores that array in localStorage
    || Displays the data then hides the "Process"
    || button and reveals the "Transfer" button
    */
    function processForm(e) {

      var qty = xCon.length;
      var data = [];
      for (let i = 0; i < qty; i++) {

        var formControl = xCon[i].value;

        if (formControl !== null || formControl !== undefined || formControl !== "") {

          data.push(formControl);

        }
      }

      localStorage.setItem("data", JSON.stringify(data));
      var stored = JSON.parse(localStorage.getItem("data"));
      appX();

      xApp.onsubmit = appX;

      function appX(e) {
        xCon.msg.value = stored;
        xCon.btn.classList.toggle('hidden');
        xCon.sub.classList.toggle('hidden');
      }
    }
    /* Once the "Transfer" button is clicked, the
    || data is sent to the test server and the
    || test server responds back. The response is 
    || captured and displayed in the iframe to the
    || right
    */
  </script>
</body>

</html>

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

1 Comment

My pleasure, happy coding

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.