Search code examples
javascripthtmlformsforeachgetelementsbyclassname

How to get values from multiple form field values using Array.from and forEach


Lets say I have a form:

<form>
  <input type="text" class="blanked">
  <input type="text" class="blanked">
  <input type="text" class="blanked">
  <input type="submit" value="Press Me">
</form>

Now lets say I use getElementsByClassName to create an array of these elements:

let filledBlanks = Array.from(document.getElementsByClassName( 'blanked' ));

Now I want to iterate through the values the user has entered into each input:

filledBlanks.forEach( filledBlank => {
  let inputText = filledBlank.???;
} 

This is where I get tripped up. What do I use to get the filled value (not .value)? Or is there a better way to accomplish this?


Solution

  • the .value property works just fine. I don't see why you would need something else. If you want to only iterate over the values, you could map your input first, but i don't see the point.

    Please note here that i'm only using Jquery to listen to the submit event. The rest is pure vanilla Javascript.

    $('form').on('submit', (event) => {
      event.preventDefault();
      
      let filledBlanks = Array.from(document.getElementsByClassName( 'blanked' ));
      filledBlanks.map((input) => {
        return input.value;
      }).forEach((value) => {
        console.log(value);
      });
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      <input type="text" class="blanked">
      <input type="text" class="blanked">
      <input type="text" class="blanked">
      <input type="submit" value="Press Me" id="submit">
    </form>