Jackson Sentzke Jackson Sentzke - 1 month ago 7
HTML Question

Get values from HTML form

I'm trying to get the values from a form I've created in HTML:
I'm using Javascript to try and get the values from the form, I've tried multiple ways of getting the values, at the moment it's this



$(document).ready(function() {
$('#submit').click(function() {
var x = document.getElementById("input");
var text = "";
var i;
for (i = 0; i < x.length; i++) {
console.log(x.elements[i].value);
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="input">
First Name: <br/>
<input type="text" name="firstName"/><br/>

Last Name: <br/>
<select id="lastName" style="text-align: center;">
</select><br/>

<p>Date of Birth:</p><br />

Day: <br/>
<select id="dayDropDown" style="text-align: center;">
</select><br/>
Month: <br/>
<select id="monthDropDown" style="text-align: center;">
</select><br/>
Year: <br/>
<select id="yearDropDown" style="text-align: center;">
</select><br/>

Country: <br/>
<input type="text" name="country"/><br/>
</form>
<br/>
<button id="submit" type="button">Submit</button>





This is meant to output the values from the form to my VS the output window, but I get nothing. any ideas?

Answer

As you're already using jQuery to attach your event handler, you may as well use it to select all the elements in the form using the :input selector. From there you can simply loop through them all using each() and output their values to the console, like this:

$(document).ready(function() {
  $('#submit').click(function() {
    $('form :input').each(function() {
      console.log($(this).val());
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="input">
    First Name: <br/>
    <input type="text" name="firstName"/><br/>

    Last Name: <br/>
    <select id="lastName" style="text-align: center;">
    </select><br/>

    <p>Date of Birth:</p><br />

    Day: <br/>
    <select id="dayDropDown" style="text-align: center;">
    </select><br/>
    Month: <br/>
    <select id="monthDropDown" style="text-align: center;">
    </select><br/>
    Year: <br/>
    <select id="yearDropDown" style="text-align: center;">
    </select><br/>

    Country: <br/>
    <input type="text" name="country"/><br/>
</form>
<br/>
<button id="submit" type="button">Submit</button>

Comments