How to dynamically add users on the page using jquery - javascript

Im having some trouble figuring this out. I have a database which has users on it and I want to display each user on the page dynamically using jquery.
Ive just thrown some user data objects in a array and im trying to call for each user object in the array to display as a list item on the page
html
<h1>List</h1>
<ul id="list">
</ul>
javascript
var user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
]
function addUser() {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user + " " + $age);
}
$.each(user, addUser());

Your mistake is very simple. You have to replace addUser() by addUser when you use the $.each method. There are also mistakes when you use the.append method. Try this code:
var user = [
{
username: "alex",
age: 20
},
{
username: "james",
age: 20
}
];
function addUser(theCase, value) {
var username = value.username;
var age = value.age;
var user = '<li> ' + username; // Use a simple string, it's better and faster!
var age = age + ' </li>';
$("#list").append(user + " " + age);
}
$.each(user, addUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h1>List</h1>
<ul id="list">
</ul>
Here you are using a callback. If you want more details about callbacks consult the MDN's documentation.
There are also several errors on .each method or .append method. Consult the documentation.
The .each method call your callback for each case on your array user. This method also provide you, in your callback, the index and the value of the case witch is treated.

Can you please check page: https://jsfiddle.net/rxcz73x9/2/
var user = [{
username: "alex", // use string
age: 20
}, {
username: "james", // use string
age: 20
}];
function addUser(idx, user) {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user).append($age); // use append for each node
}
$.each(user, addUser); // use function name instead of addUser()
I've added comment that could help you with example above.

When you pass a callback to the jQuery each function, what happens is that the callback is going to be invoked with every element in your user array.
Check the arguments that jQuery.each passes to the callback. The callback function signature should expect the index and the value of the element in that index.
For example:
var users = user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
];
function addUser(index, user) {
// do what you want and in the end
$('#list').append(/* an <li> element */);
};
// Now pass the function as a callback, but don't invoke it.
$.each(users, addUser);

Related

I am unable to implement the forEach loop in JavaScript

This is the image of the array named database I am using
I don't know how to use the forEach loop properly, can someone say why this does not work?
This is what I tried.
var database = [{
username: 'gaurav',
password: 'password'
}, {
username: 'gaurav1',
password: 'password1'
}, {
username: 'gaurav2',
password: 'password2'
}];
database.forEach(credential => {// credential is the object = {username, password}
if (credential.username === credential.username && credential.password === credential.password) {
console.log('matched');
}
})
forEach will expect function having array of objects as "database" is having collection of objects. So we cannot have 2 separate parameters as you are passing "function (username, password)". It should be function(obj).
The reason your forEach loop doesn't work is that you are passing it a function that looks like this:
function f(user, password) {
password == 'examplepassword';
user == 'someuser';
}
Your function is taking the wrong parameters. forEach goes over an array, and passes each item of the array to the function you are giving it. The function should be instead written like:
function f(item) {
item.password == 'examplepassword';
item.user == 'someuser';
}
So you would want to rewrite your code to be more like
db = [{username: 'a', password: 'abc'}, {username: 'b', password: 'bca'}]
db.forEach(function(user) {
console.log("user " + user.username + " has password " + user.password);
})
/* Output:
user a has password abc
user b has password bca
*/
Extra credit:
You can find more details in the documentation for forEach. The function you pass forEach can also have two other arguments, the nÂș of the item it is currently passed, and the original array.
let a = ['a', 'b', 'c']
function f(item, position, array) {
console.log("The letter " + item + " is in position " + position)
console.log("array[position] == " + array[position])
}
a.forEach(f);
/* Output:
The letter a is in position 0
array[position] == a
The letter b is in position 1
array[position] == b
The letter c is in position 2
array[position] == c
*/

How to create a list of contacts using javascript?

I've got to create a list of contacts using javascript which allows the user to enter contacts, and so that the program runs until the user quits. I'm a little lost as to whether I need to add alerts or not. Here's some of my code below, it's a work in progress so there are no expected console outcomes from it as yet.
/*
Activity: Contact manager
*/
// TODO: Complete the program
var Contact = {
// initialise contacts
init: function(last_name, first_name) {
this.last_name = last_name;
this.first_name = first_name;
},
describe: function () {
var description = this.last_name + "," + this.first_name;
return description
},
// add a contact
contact_list: function () {
var list_of_contacts = []
}
}
var contact1 = Object.create(Contact);
contact1.init("Smith", "John");
var contact2 = Object.create(Contact);
contact2.init("Doe", "Jane");
var contact_list = [];
contact_list.push(contact1);
contact_list.push(contact2);
This is what the console should look like, if the exercise is completed successfully:
Welcome to your contacts manager!
1: List contacts
2: Add a contact
0: Quit
Upon providing the option 1:
Here's the list of all your contacts:
Last name: Smith, first name: John
The rest is almost identical.
You already have a list, you are pusing them to the array: contact_list.push(contact1);
In order to log output a list, all you have to do is loop the array and print each name;
let output = "contacts: ";
for(let i=0;i< contact_list.length; i++){
output+= "Last name:" + contact_list[i].last_name + ", first name:" +contact_list[i].first_name ;
}
console.log(output);

Update 'nested' javascript object dynamically

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}

Dynamically add link with String parameter

I have a REST backend link mywebsite/guests, which returns list of guests. In the front end, I want to display the guests as links. Here's the code
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(' + guest.id + ')">' + guest.name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
I should mention that guest.id is a string.
The console always print undefined. My question, how can I add these links with String parameters?
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(this)" data-id='+guest.id+'>' + guest.name + '</a><br>')
}
function showGuest(this) {
console.log($(this).data('id'))
}
The main issue is that you are trying to access the property of dynamically bound DOM elements in your showGuest(id) function. You should use the onClick function in the following way-
var guests = [{"id":1, "name":"John Doe"},
{"id":2, "name":"David Jones"}];
for(guest of guests) {
$('#guest_list').append('<a class="guest" data-id="'+guest.id+'">' + guest.name + '</a><br>');
}
$('#guest_list').on('click', 'a.guest', function() {
var id = $(this).attr('data-id');
$('.message').text('').append("Clicked guest with ID: "+id);
});
Working JSFiddle here - https://jsfiddle.net/2dkpsve8/
Hope this helps!
The way to approach this problem depends on the format and content of the guests variable. If you started with this object:
var guests = {
'123': {id: 123, name: 'joe'},
'234': {id: 234, name: 'jane'}
};
Then key would be "123" and "234" in the following loop, and the object values would be guests[key]:
for(var key in guests) {
$('#guest_list').append('<a onclick="showGuest(' + guests[key].id + ')">' + guests[key].name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
But if you're already using jQuery, take a look at jQuery.each for another looping option.
On the other hand, if guests is an array, as in:
var guests = [
{id:"123", name:"joe"},
{id:"234", name:"jane"}
];
then you will just want to use something like:
for(var i=0; i < guests.length; i++) {
// id is guests[i].id
// name is guests[i].name
}
Amazingly,
$('#guest_list').append('<a onclick="showGuest(' + "guest.id" + ')">' + guest.name + '</a><br>')
works fine! I don't know way. "guest.id" is replaced by the actual id of guest.

I don't understand this function. [Codecademy Contact List excercise]

So the "for var x in friends" loop is going to search each key inside friends, which would be bill and steve, and then with "friends[x].firstName === name" we are checking if the first name is equal to "name", but how does the program know if "name" is Steve or Bill? I'm missing something here.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: " ",
address: [' ', ' ', ' ',' ']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: " ",
address: [' ', ' ', ' ',' ']
}
};
var list = function(friends) {
for (var x in friends) {
console.log(x);
}
};
var search = function(name) {
for (var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
for (var x in friends)
This iteates over all keys in friends, resulting in two loop iterations with
x = "bill"
x = "steve"
Then with friends[x] in the loop you access friends.bill and freinds.steve.
The name variable is given as a parameter to search(name). This effectivly searches all entries in the dict friends for firstName == name.
here we have defined search as a function search which accepts an argument name .
var search = function(name)
and we use the function like
search('Bill')
So the function knows which name we are looking for, which is Bill . It will iterate through each item and compare each firstName with Bill. It returns the corresponding friends[x] , when it finds a match .
The advantage of function with parameter is that, with the same function we can search for any name . ex : search('Steve') , search('Bill') .
if you don't understand functions with parameters, revisit the codeacademy section understanding parameters - js

Categories