Victoravna
Victoravna

Reputation: 35

Is it possible to populate an Object instance by looping through an array?

I'm making a journal app and need to create an object instance every time inputs are submitted on my html form.

I want to create a loop that takes the inputs in results and converts them to values in a new Object instance. My attempt at this so far gives me an instance with undefined values however. Is this even possible to do?

results = []

function example(a, b){
    this.a = a;
    this.b = b;
}

function getElements(){
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
results.push(a,b)
}

My attempt at a loop to create a new instance of example

function createNewDay(){
    for (i = 0;i<results.length;i++){
    var x = new day([i])
    }
}

When I console.log => example{a:undefined, b:undefined}

Upvotes: 0

Views: 59

Answers (3)

trincot
trincot

Reputation: 350137

You can use FormData for this -- which makes it a more general solution:

var form = document.querySelector('form');

form.onsubmit = function () {
    var formdata = new FormData(this);
    var results = {};
    for ([key, value] of formdata) {
        results[key] = value;
    }
    console.log(results);
    return false; // cancel submission
};
<form method="post" action="">
    a: <input name="a" value=""><br>
    b: <input name="b" value=""><br>
    <input type="submit">
</form>

Upvotes: 0

Per &#214;stlund
Per &#214;stlund

Reputation: 1224

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input id="a" type="text">
  <input id="b" type="text">
  <button type="submit" id="submit">Submit</button>
  <button type="button" id="view">View results in console</button>
</body>
<script type="text/javascript">
var results = [];

function Example(a, b) {a
  this.a = a;
  this.b = b;
}

function getElements() {
 var a = document.getElementById('a').value;
 var b = document.getElementById('b').value;
 results.push(new Example(a, b));
}

function loopResults() {
  for (var i = 0; i < results.length; i++) {
    console.log(results[i]);
  }
}

document.getElementById('submit').addEventListener('click', getElements, false);
document.getElementById('view').addEventListener('click', loopResults, false);
</script>
</html>

Demo: http://jsbin.com/jehupayomu/1/

Upvotes: 1

Vladimir M
Vladimir M

Reputation: 4489

So... you can use jquery for that:

var formDataObject = $("refer_to_form_by_id_or_name").serializeObject();

Like mentioned in here: Serialize form data to JSON

Upvotes: 0

Related Questions