jward01 jward01 - 4 months ago 16
Javascript Question

How to store HTML form input as JavaScript Object

I am self learning JS and working on an exercise which takes input from the user(First Name, Middle Name, Last Name), and saves the input in a JS Object (Later I will manipulate the object itself and sort it, check duplicates, etc.)

I have looked everywhere and cannot find any direction on this one. I am familiar with saving HTML input as variables (var n=document.getElementById('x').value) but I am very new to objects.

How would I save user input in objects? And can I save multiples 'submissions' in the Object as in 'load the object up from user input', and then manipulate it on a later step?

HTML:

<body>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" onclick="buildList()">Add to List</button>
</body>


What I imagine the JS Object to look like, and each time the user presses 'Add to List' the program adds another First/Middle/Last name to the list.:

var list = {
firstName:"John",
middleName:"Will",
lastName:"Doe"
},
{
firstName:"Ben",
middleName:"Thomas",
lastName:"Smith"
},
{
firstName:"Brooke",
middleName:"James",
lastName:"Kanter"
};


***Note, later on I plan to count the frequency of each First/Middle/Last Name and output it on the screen.. i.e.:
'FirstName'Jason: 2, 'FirstName'Ed:3; 'MiddleName'Marie:5; 'LastName'Smith:3'


My goal: Create a list of full names. Break them out into three lists: first, middle, and last names. Count the frequency of the names in each list. ---I figured using an object would be the best way to do this.

Answer

You could use a click handler like

var list = [],
  $ins = $('#firstName, #middleName, #lastName'),
  counter = {
    firstName: {},
    middleName: {},
    lastName: {}
  };
$('#add').click(function() {
  var obj = {},
    valid = true;
  $ins.each(function() {
    var val = this.value.trim();
    if (val) {
      obj[this.id] = val;
    } else {
      var name = this.previousSibling.nodeValue.trim();
      alert(name.substring(0, name.length - 1) + ' cannot be blank');
      this.focus();
      valid = false;
      return false;
    }
  });
  if (valid) {
    list.push(obj);
    $ins.val('');

    $.each(obj, function(key, value) {
      var count = counter[key][value] || 0;
      counter[key][value] = count + 1;
    });

  }
});

$('#print').click(function() {
  $('pre').text(JSON.stringify(list) + '\n\n');
  $('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
  white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
  <input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
  <input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
  <input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>

<pre></pre>

Comments