Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  189] [ 1]  / answers: 1 / hits: 41017  / 12 Years ago, sun, november 4, 2012, 12:00:00

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.


More From » arrays

 Answers
30
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


[#82207] Friday, November 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
beatriceisabelad

Total Points: 710
Total Questions: 107
Total Answers: 99

Location: Cayman Islands
Member since Sat, Sep 17, 2022
2 Years ago
;