Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding multiple values to single array item in javascript

I am having trouble with output of an array, I think.

What I would like the output to look like is:

1. FirstName LastName DOB

but what I end up with is:

1. FirstName
2. LastName
3. DOB

Here is what I have so far but I am not seeing what I am doing wrong.

// global variable:
var tasks = []; 

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
    'use strict';

    // Get the task:
    var firstName = document.getElementById('firstName');
    var lastName = document.getElementById('lastName');
    var dob = document.getElementById('dob');

    // numerical value of dob
    var dateofBirth = new Date(dob.value);

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (firstName.value && lastName.value && dob.value) {

        // Add the item to the array:
        tasks.push(firstName.value, lastName.value, dateofBirth.toString());


        // Update the page:
        message = '<h2>Persons Entered</h2><ol>';
        for (var i = 0, count = tasks.length; i < count; i++) {
            message += '<li>' + tasks[i] + '</li>';
        }
        message += '</ol>';
        output.innerHTML = message;

    } // End of IF.

    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;

Thanks, I hope this helps you to help me.

like image 606
punktilend Avatar asked Feb 19 '23 14:02

punktilend


1 Answers

tasks.push({firstName: firstName.value, lastName: lastName.value, DOB: dateofBirth.toString()})

And then

tasks[0].firstName will output firstName.value
tasks[0].lastName will output lastName.value 

etc..

Edit

Using this, you can then construct your messasge like this :

for (var i = 0, count = tasks.length; i < count; i++) {
    message += '<li><span>' + tasks[i].firstName + '</span><span> ' 
    + tasks[i].lastName + '</span><span>' + tasks[i].DOB + '</span></li>';
}

Of course, the span tags are optionnal but this will allow you to apply a style to each part of the information in your css (width, padding, etc..) and you will always be able to easily select a property of a task by index

like image 143
Yann Avatar answered Apr 27 '23 17:04

Yann