1

I've got a form that takes input from the user

<form id='myForm'>
        <div id='x'>
                 <h2> start </h2>
            <ul class="rounded">
                <li><input type="text"  placeholder="text" id="o" /></li>
            </ul>
                <h2>dests </h2>
            <ul class="rounded">
                <li><input type="text"  placeholder="text" id="d" /></li>
            </ul>
            <ul class="rounded">
                <li><input type="text"  placeholder="text" id="d" /></li>
            </ul>
        </div> 
<li class="arrow"><a href="#page2" onclick='function()'>Run </a></li>
</form>

I need a way of getting the user input from every field in the form, and placing it into an array. I have looked into getElementByTagName('input'), but this returns a HTMLCollection object. Any suggestions? (P.S i'm using a jqtouch if you're wondering what's up with the weird syntax)

4
  • 1
    I see you have two input with the same id. id's should be unique, also what have you tried so far? Where is your javsascript to go with this? Commented Dec 27, 2016 at 16:24
  • You have several elements having the same ID Commented Dec 27, 2016 at 16:24
  • As they've mentioned in the comments, you have several controls with the same id. You can try the line of codes below. var inputControls = $('#myForm').find('input[type=text]'); var inputArray = []; $.each(inputControls, function(index, value){ var inputValue = $(item).val(); inputArray.push(inputValue); }); Commented Dec 27, 2016 at 16:30
  • Do they have to be unique? The form is dynamic (users can add more dests) so its difficult to increment the id as the users adds more dests. Commented Dec 27, 2016 at 16:30

5 Answers 5

1

You can use Array.prototype.map to create an array from the list of input elements obtained from querySelectorAll.

Try filling the inputs and clicking Run in the demo below:

var elements = document.querySelectorAll('#myForm input');

function callme() {
  var result = Array.prototype.map.call(elements, function(e) {
    return e.value;
  });
  console.log(result);
}
<form id='myForm'>
  <div id='x'>
    <h2> start </h2>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" />
      </li>
    </ul>
    <h2>dests </h2>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" />
      </li>
    </ul>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" />
      </li>
    </ul>
  </div>
  <ul>
    <li class="arrow"><a href="#page2" onclick='callme()'>Run </a>
    </li>
  </ul>
</form>

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

Comments

1

As others have mentioned be careful to use the html id attribute with a unique id, i.e. each input should have its own.

Using vanilla JavaScript, document.getElementsByTagName() returns a live html collection and you can access its members as properties using [index] to get the element you want. Then use textObject.value to access the inputs' value.

All in all, document.getElementsByTagName('input')[0].value will provide the value of the first input! That is the logic, also check the snippet.

Please also consider the following:

  • element.querySelectorAll() is generally slower than element.getElementsByTagName(), as the first uses a depth-first pre-order traversal of the document's nodes
  • element.querySelectorAll() returns a StaticNodeList

I found this article quite interesting for this topic.

function retrieve(){
  let list = document.getElementById('inputListContainer');
  let input = list.getElementsByTagName('input');
  let array = [];
  for( let i = 0; i < input.length; i++ ){
    //input[i].value is the same as document.getElementsByTagName('input')[i].value
    array.push(input[i].value); 
  }
  console.log( array );
}
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id='inputListContainer'>
      <!-- Using a single ul to parent list items. Note that this does not affect the script -->
      <ul id='inputList' class='rounded'>
        <li><input type="text"  placeholder="one"/></li>
        <li><input type="text"  placeholder="two"/></li>
        <li><input type="text"  placeholder="three"/></li>
      </ul>
      <button onclick='retrieve()'>Retrieve</button>
    </div>
  </body>
</html>

Comments

0

Try this:

function getValues() { 
  var values = []; // Array of input values
  var elements = document.querySelectorAll("#myForm input");

  for(var i = 0; i < elements.length; i++) {
    values.push(elements[i].value);
    //If you need the input ID:
    //values.push({name: elements[i].id , value: elements[i].value});
  }
}

4 Comments

If I were you I would swap getElementsByTagName('input'); with document.querySelectorAll("#myForm input"); otherwise this will get all inputs from the page. The OP is wanting to get all the inputs from the form.
Nice catch! Thanks @NewToJS
Very welcome, your original answer was pretty close so rather than me submitting the same but have a minor change I thought it would be easier to post a comment :) To be honest I would add some information about using querySelectorAll() and a working snippet. Seeing the demo and a detailed answer seem to be more valued. If you choose not to update your answer I will be submitting a details one.
@NewToJS Agree with you. A working snippet with details can be helpful in order to better understand how it works.
0

For this you can use Document.querySelectorAll()

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

Using document.querySelectorAll("#myForm input"); will target all inputs within the form with the ID of myForm.

Then a for() loop is used to iterate through the collection and push the input values into the array .

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

for ([initialization]; [condition]; [final-expression]) statement

function BuildArray() {
  var myArray = [];
  var input = document.querySelectorAll("#myForm input");
  for (var i = 0; i < input.length; i++) {
    myArray.push(input[i].value);
  }
  console.log(myArray);
}
<form id='myForm'>
  <div id='x'>
    <h2> start </h2>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" id="o" value="first" />
      </li>
    </ul>
    <h2>dests </h2>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" id="d" value="second" />
      </li>
    </ul>
    <ul class="rounded">
      <li>
        <input type="text" placeholder="text" id="d" value="third" />
      </li>
    </ul>
  </div>
  <li class="arrow"><a href="#page2" onclick='BuildArray()'>Run </a>
  </li>
</form>

I would also like to recommend keeping ID's unique if ID's are required but for this task ID's are not used in the selector so no problems if ID's are the same.

If you have any questions about the source code above please leave a comment below and i will get back to you as soon as possible.

I hope this helps. Happy coding!

Comments

-1

You just need to iterate through each input and push each value into an array. You would call something like this on click. See jQuery example here.

function click() {
   var arr = [];

   $.each($('input'), function(k,v) {
      arr.push($(v).val());
   })

   console.log(arr);
}

1 Comment

jQuery isn't tagged in this question.

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.