Get All Input Values Inside a Div – Javascript Solution

Want to quickly snatch up your input values to output on screen or save into an array. Look no further, I’ve got a solution for you. 

This was quite a pain to get working. And by pain, I mean super fun to resolve and time consuming. 

My Project

For my purposes, I need to grab all values that resulted from a calculator I created for a client project. I need it to work for multiple calculators no matter how many input results they output. 

My goal here was to grab the label of the input, the value of the input and add it to an array as a string per result. I can then do a javascript ajax post and grab that array with my php script housed in my theme files. This PHP script is set to send an email to the user showing with their results. 

So no matter which calculator they use, if they opt to enter their email and have the results sent to them, they will get all input values.

So let’s take a look at the code.

First things first

Using innerHTML will not work. innerHTML will only grab what was rendered by the browser to keep it simple.

innerText similarly works and won’t help you get input values.

Now that that’s out of the way, let’s see how we can actually make this work….

Grab all input values within a div (get the input label too)

Here’s how to get all input values and input titles seamlessly with a simple javascript loop.

There’s very little setup. Just make sure you have a div with a unique id which contains the inputs. 

Now, first we will create an array which will grab all the values (if applicable). 

const allValues = [];
allValues[0] = jQuery(".calc-title h2").text();  //Again, only if applicable. I wanted to have the calculator title in there as well so I set it first in the array
allValues[1] = document.getElementById("user_email").value;  //I set their email 2nd in the array for later use in the PHP file
var i = 3;   //I set this to "3" because I plan on using allValues[3] to store the amonut of inputs after the loop is complete. So...we start on 3.

With that done, we can move onto the loop. It’s rather simple (in terms of how short it is). We go through each ‘input’ inside of ‘#yourdiv’ and grab the label for that input we are currently on and the get the value of that input in fell swoop, creating a single string and adding it to the array. Then we iterate through. 

Here’s the code:

jQuery('#yourdiv input').each(function() {     
allValues[i] = jQuery("label[for='" + jQuery(this).attr('id') + "']").text() + ': ' + jQuery(this).val();    
i++; });
allValues[2] = i - 3;

 

Hope that helps! If you have questions, please make a comment below.

 

Share