6

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.

6
  • 2
    @jward01 something like this? jsbin.com/vaxulusoma/edit?html,js,console,output Commented Jul 10, 2015 at 4:35
  • @bassxzero good code, but you don't need to save objects in hidden input, you can use global variable. Commented Jul 10, 2015 at 5:04
  • @shyammakwana.me I'm aware of this, but considering that OP was having trouble understanding where/how to store data client side, I wanted to make this as clear/simple as possible. Thank you though Commented Jul 10, 2015 at 5:08
  • @bassxzero Yes!! Just like that!! Thank you very much for writing that and showing me how it works. Now I just need to examine it and understand how and why it works so that I can master it as you have!! Im sure its very simple once one gets the jist of it. Thank you Very much! Commented Jul 10, 2015 at 16:22
  • @shyammakwana.me -- What do you mean by 'hidden input?' thanks!! Commented Jul 10, 2015 at 16:24

6 Answers 6

4

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>

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

1 Comment

Can anyone provide me the same logic by without JQuery. In Simple JS Object.
2

Js objects are very easy to manipulate (which many times makes it prone to more errors). If you want to add a property just put some value on it.

var info = {};//create an empty object
info.firstName = document.getElementById('firstName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);//you had to initialize the array before

Comments

0

If your goal is to map the frequency of each name, using three hashes might be the most efficient option. As an example for just one of the inputs:

var firstNames = {};

function setFirstName(firstName){

    if(firstNames[firstName] === undefined){
        firstNames[firstName] = 1;
        return;
    }
    firstNames[firstName]++;
}

function buildList(){

    setFirstName(document.getElementById('firstName').value);

}

That way you'll end up with something like var firstNames = {tom: 3, dick: 10, harry: 2, ...}. Here's a fiddle: https://jsfiddle.net/n3yhu6as/2/

Comments

0

You could create an object from the inputs (as they look in given markup), like:

function buildList(){
        var list = {};
        $("body").find("input").each(function() {

            var field= $(this).attr('id');
            var value= $(this).val();
            list[field] = value;
        });
}

fiddle.

1 Comment

In his application, this would overwrite the the firstName property value each time the button was pressed-as opposed to adding it to a list and maintaining a count.
0

There is a difference between [] and {}

The push() method and length property is only applicable to [] becuase it actually the JavaScript array

Therefore in your case you should put your JSON Object inside a JSON Array

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

If you do like this then you do code in your button click event as

list.push({
    firstName: document.getElementById("firstName").value,
    middleName: document.getElementById("middleName").value,
    lastName: document.getElementById("lastName").value
});

Comments

0

how to search for a particular keyword from the user provided name fields.

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

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.