I made a HTML project called Customer with some text boxes where can I enter some text and a button called save.Now I want to create a function in JavaScript to save a new contact object.
I tried this:
function SaveContact() {
var list = [];
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
var phoneN = document.getElementById("phone");
var emailN = document.getElementById("email");
var birthDay = document.getElementById("birth_day");
var birthMonth = document.getElementById("birth_month");
var birthYear = document.getElementById("birth_year");
list.push({ firstName, lastName, phoneN, emailN, birthDay, birthMonth, birthYear });
return list;
But it doesn't change anything. Where am I wrong?
The problem with the following line:
list.push({ firstName, lastName, phoneN, emailN, birthDay, birthMonth, birthYear });
is that you're only saving values. In JS, you need both values and keys. Therefore, you would need to change it to:
list.push({ "firstName": firstName, "lastName": lastName, "phoneN": phoneN, "emailN": emailN, "birthDay": birthDay, "birthMonth":birthMonth, "birthYear":birthYear });
EDIT
You say you want to create an object but you want to store them as an array. To store them as an array (an object with keys as their indeces), just remove the { and } in the push() line.
However, I think it would be easier to just create an object, like so:
function SaveContact() {
return {
"firstName": document.getElementById("first_name"),
"lastName": document.getElementById("last_name"),
"phoneN": document.getElementById("phone"),
"emailN": document.getElementById("email"),
"birthDay": document.getElementById("birth_day"),
"birthMonth": document.getElementById("birth_month"),
"birthYear": document.getElementById("birth_year")
};
}
This one-statement function simply creates and returns an object literal, rather than assigning the values to variables and then putting them into an array/object.
But if you really do want an array, just replace the { and } with [ and ] and remove the keys. This will get you the output you are currently trying to achieve with your program.
Push does not need the { ... } around the elements:
array.push(item1, item2, ..., itemX)
(from here)
Also, note that you are storing DOM Elements in the the list. You probably need their values and not the elements but it depends on what you try to do...
EDIT - after seeing Jonathan's answer
Alternatively you can do:
obj = {}
obj.name = document.getElementById("first_name")
// ... more fields
list.push(obj)
Related
I have a form to collect Family information from a form which will eventually be used to enroll in a new benefit plan. I want to populate an array with the values required for each individual to be used to write the benefit record. Everything I've found so far simply creates array values and increments the index for each one. What i need to do is add multiple elements to each array index.
The initial code I tried doesn't work. I'm taking the values from the form which are there but when I try to create the array row it errors out
I need to know how to accomplish this
When I try to execute I get " Unable to set property 'fname' of undefined or null reference
I know I'm not doing this according to Hoyle but I can't seem to find the correct method.
How do I do this.
function ValidateChgFAM()
{
formObj = self.MAIN.document.SSform2;
var Fname = formObj.FirstName11.value
var Lname = formObj.LastName11.value
var Gender = formObj.Gen11.value
var famMbrs = new Array();
famMbrs[0].fname = formObj.FirstName11.value
famMbrs[0].lname = formObj.LastName11.value
famMbrs[0].gender = formObj.Gen11.value
famMbrs[0].birthdate = formObj.Birthdate11.value
famMbrs[0].seq = "01"
When I try to execute this I get the message " Unable to set property 'seq' of undefined or null reference.
I don't live with Javascript but I've been work with this system and I can normally figure stuff out.
A simpler and more elegant solution:
const famMbrs = [];
const member = {
fname: formObj.FirstName11.value,
lname: formObj.LastName11.value,
gender: formObj.Gen11.value,
birthdate: formObj.Birthdate11.value,
seq: '01'
}
famMbrs.push(member)
Will result in:
Array(
0: {
fname: (value),
lname: (value),
gender: (value),
birthdate: (value),
seq: '01'
}
)
I was trying to access sub-properties from a javascript file and it's giving me something weird!
Suppose this is my JS file named data.js
module.exports = {
something: {
name: "Something",
num: 1,
email: "something#gmail.com"
},
somethingtwo: {
name: "Something Something",
num: 2,
email: "somethingtwo#gmail.com"
},
};
In my main js file named app.js, where I need to access it, it looks like
var persons = require('./data.js');
var getAName = function() {
for(var name in persons) {
console.log(name.email);
}
}
I really don't know what goes wrong but I have been trying this for quite a long time now. The expected output is the email Ids from the data.js file but instead, i get undefined times the number of entries (if there are 2 entries in data.js, then I get 2 undefine and so on).
How can I access the email or the num from the data.js without those undefines?
console.log(name) is returning something somethingtwo
Well, name.email is undefined because name is a string.
You can test that by writing
console.log(typeof name);
Now, to solve your problem, you need to access the property correctly:
var getAName = function() {
for (var name in persons) {
console.log(persons[name].email)
}
}
Returns:
something#gmail.com
somethingtwo#gmail.com
for(var name in persons) {
//persons is actually an object not array
//you are actually iterating through keys of an object
//var name represent a key in that object
console.log(persons[name]); //value corresponding to the key
}
I guess this code will give you the desired result.
You should be using console.log(persons[name].email)
require don't automatically calls the module
var DataArchive = require('./data.js');
var module = DataArchive.module;
var persons = module.exports;
var getAName = function() {
for(var person in persons) {
//person should be something (first iteration) and somethingtwo (second iteration)
console.log(person.email);
}
I'm trying to create an object that is updated dynamically.
Here's the setup of the type of object I'd like to create (note: I may add other things, such as address, country, etc to the keys):
var contacts = {"Bruce Wayne":{"phone number":'123-456-7890', "email":"bwayne#night.com"}, "Alfred":{"phone number" :'987-654-3210', "email": "alfred#yourang.com"}, "Clark Kent":{"phone number":'951-753-8520', "email":"nothing#krypton.com"}}
So for each name (Bruce Wayne, Alfred, ...) I have some keys assigned to them.
I'm using npm faker to generate some fake data to try and populate an array like the above, with the outline
I'm able to get a loop going, but it always returns the last iteration's data. I understand it's because I'm doing contact = .... Since this is an object, I can't use push, AFAIK.
function getContact(numContacts){
contacts = {}
for (var i = 0; i < numContacts; i++){
console.log(i);
var name = faker.name.firstName() + " " + faker.name.lastName();
var phoneNum = faker.phone.phoneNumber();
var email = faker.internet.email();
contacts = {name :{ "phone number": phoneNum, "email": email}}
// contacts.name = {"phone number": phoneNum, "email":email}; // this also returns just the last instance.
};
return contacts;
};
var contacts = getContact(10); // This should create ten people, each with a phone number and email.
The loop almost successfully creates a single name. This returns:
name, 761.704.3328 x4287, Leopold81#hotmail.com
But in that iteration, name variable is actually Joe Schmoe, not literally name...
What am I overlooking to make sure that the contacts object gets populated with 10 people, with the resolved name, not just the last in the iteration?
Observations
You're trying to use name variable as key, however, what you're doing is adding a key literally called name.
What you have to do, is to create the key programmatically as follow: contacts[name] and assign the object with phoneNumber and Email.
This code is an example to simulate your scenario.
var faker = {
name: {
firstName: function() {
return "Clark";
},
lastName: function() {
return "Kent";
}
},
phone: {
phoneNumber: function() {
return '951-753-8520';
}
},
internet: {
"email": function() {
return "nothing#krypton.com";
}
}
};
function getContact(numContacts) {
var contacts = {}
for (var i = 0; i < numContacts; i++) {
var name = faker.name.firstName() + " " + faker.name.lastName();
var phoneNum = faker.phone.phoneNumber();
var email = faker.internet.email();
contacts[name + '_' + i] = {
"phone number": phoneNum,
"email": email
}
}
return contacts;
}
var contacts = getContact(10);
console.log(contacts);
The names are the keys in your object. You can use it like an array index to populate contacts. This should work:
contacts[name] = {"phone number": phoneNum, "email": email}
Using JavaScript I am pulling names out of webpage and stringing them together somehow (probably going with an array). Once I gather all the names together I need to make another string that gives all the email addresses of the names. The email addresses are not on the webpage so I will have to list every possible thisName=thisEmail in my script somehow. I was about to approach this with making a bazillion if statements but I thought there has to be a more efficient way. Any suggestions?
var x = getElementById("names");
var name = x.InnerHTML;
var email;
if (name == 'Steve'){ email == 'steve462#gmail.com'; }
if (name == 'Bob'){ email == 'duckhunter89#gmail.com'; }
....
A switch statement, as your code is only if-elses :-)
No, honestly. The best thing would be if you'd find a simple algorithm to create an email address from any given name, like
function mail(name) {
return name.toLowerCase() + "#gmail.com";
}
var email = mail("Bob") // example usage
If they differ to much, you might use an object as a key-value-map:
var mails = {
"Steve": "steve#gmail.com",
"Bob": "bob1#freemail.org",
...
}
var email = mails[name];
You could also combine those, if you have to determine which algorithm you need to use:
var map = [{
algorithm: function(name) { return name+"#something"; },
names: ["Steve", "Bob", ...]
},{
algorithm: function(name) { return "info#"+name+".org"; },
names: ["Mark", ...]
}];
for (var i=0; i<map.length; i++)
if (map[i].names.indexOf(name) > -1) {
var email = map[i].algorithm(name);
break;
}
or when it is a bit simpler:
var domains = {
"gmail.com": ["Steve", "Bob", ...],
"free.xxx": ["Mark", ...],
...
};
for (var domain in domains)
if (domains[domain].indexOf(name) > -1)
var email = name.toLowerCase()+"#"+domain;
break;
}
Just try to reduce the amount of data to deliver to the client as much as you can.
You can store all the email address in an associative array like
pseudo code
var emailsList = ["steve" => "steve#gmail.com", "bob" => "bob#gmail.com"];
then email = emailsList[name]; will solve your problem
You could create an object in advance:
var name_email_map = {
"Steve": "steve#gmail.com",
"Bob": "bob#gmail.com",
"John": "j7hogli123123#telus.net"
}
This would be easy to output from some server side language with a JSON library for whatever language you're using. There is a list of JSON libraries at the bottom of this page: http://www.json.org/
If you're using PHP on the server side you can just json_encode an associative array, which you may have selected from a database.
var name = 'Bob'; //x.innerHTML;
var email = name_email_map[name];
alert(email); // Alerts bob#gmail.com
alert(name_email_map['John']); // Alerts j7hogli123123#telus.net
I am working on codeAcademy's javascript section and I am so stuck on one of the exercises.
Here is my code:
var friends = {
bill:{
firstName:"Bill",
lastName: "Gates",
number:"(206)555-5555",
address:['One Microsoft Way', 'Redmond','wa','12345']
}
};
var friends = {
steve:{
firstName:"Steve",
lastName: "Jobs",
number:"(555)555-5555",
address:['One Apple Way', 'San Diego','ca','12345']
}
};
var list = function()
{
for (var something in friends)
console.log(something);
}
var search = function(name)
{
for (var contact in friends)
{
if (contact == name)
{
for (var contact_info in friends.name)
{
console.log(contact_info);
}
}
}
}
I am pretty confused about the for/in loop. I have been working on this exercise for a while and was wondering if someone could help me understand. Mainly the search function. Its suppose to be able to see if the given name is in the the object and print the contact info associated. I am completely lost. I even tried restarting the whole section and still got stuck.
In Javascript, the for-in loop will go through each of an object properties.
Your friends object is first created having only one property, which is also an object, describing Bill Gates. Then it it overwritten by another object that also has only one property, but now describing God Steve Jobs.
Finally, in the search function, you are going through each property of friends and comparing them to a string. Inside a for-in loop, name is a variable that contains the name of the property used in the current iteration of the loop. So you'll get a match if you use the names of the variables (i.e.: steve). If you wish to match the names stored in the object, you have to use a parameter that is not called name in the declaration of the search function, and make the check like this:
if (contact.firstName == _name || contact.lastName == _name ||
(contact.firstName + " " + contact.lastName) == _name)
Also notice that after you create your friends variable with Bill, you then recreate it with Steve. So you end up with only one "contact" in that variable. You could change your object declarations like this:
var friends = {}; // This creates an empty object
friends.bill = {
firstName: "Bill",
lastName: "Gates" // And so on...
};
friends.steve = {
firstName: "Steve" // You get the drill
};
And then your friends object would have both pirates of the Sillicon Valley now.
First of all you have wrong friends var definition, you override Bill with Steve.
It suppose to be similar to this
var friends = {
bill:{
firstName:"Bill",
lastName: "Gates",
number:"(206)555-5555",
address:['One Microsoft Way', 'Redmond','wa','12345']
},
steve:{
firstName:"Steve",
lastName: "Jobs",
number:"(555)555-5555",
address:['One Apple Way', 'San Diego','ca','12345']
}
};
Now the answer to your question.
function search(name)
{
// Length of friends object received using Object.keys
for (var p = 0; p < Object.keys(friends).length ;p++)
{
if(friends[name] != undefined){
// Add to console and stop function execution if match found.
console.log(friends[name].firstName);
return;
}
}
}
Some explanation.
If "friends[name]" is undefined it means that you don't have object with specified name.
If it returns some Object you just get the value of the "firstName" or any other property in the object.
A for in loop in Javascript will loop through each property of an object. Unfortunately, your object will only have 1 property steve because you overwrite the entire object with your second var friends = ... statement. When looping through an object, your name variable will be the string index of your friend in the friends object. Once you find a match for the name, you can use the contact information by using friends[name]. If you are looking for a friend with the same first name as your search, you may want to look at the specific first name
Just as a side note, because Javascript is a loosely typed language, there is no need to loop through the entire friends object to see if you have a friend with that name. Here is a code sample:
var friends = {
bill: {
firstName: 'Bill',
lastName: 'Gates'
},
steve: {
firstName: 'Steve',
lastName: 'Jobs'
},
steve2: {
firstName: 'Steve',
lastName: 'Doe'
}
},
search1 = function(name) {
if(friends[name] !== undefined) { //Is there a friend with this index
//Yay, we have a friend with this index!
}
else {
//Sorry, we don't have a friend with this index
}
},
search2 = function(name) {
name = name.toLowerCase(); //Case insensitive
for(var friend in friends) {
if(friends[friend].firstName.toLowerCase() == name) { //Does this person have the same first name
//This friend has the same first name
}
}
};
search1('steve'); //Will only give us Steve Jobs
search2('steve'); //Will give us Steve Jobs and Steve Doe