when a given array includes a list of employees
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
and #ul is already provided,
<ul id="container">
<li>
<a class="name">John Doe</a>
<div class="age">41</div>
</li>
<li>
<a class="name">Mary Jane</a>
<div class="age">20</div>
</li>
</ul>
I need to return a role of an employee when employee's name is clicked. here is my code
function findRoles(array) {
const container = document.getElementById('container');
for (let i = 0; i < array.length; i++) {
const li = document.createElement('li'),
a = document.createElement('a'),
div = document.createElement('div');
ul = document.createElement('ul');
let user = array[i];
a.innerText = user.firstName + ' ' + user.lastName;
a.className = 'name';
a.addEventListener("click", () => printRole(user))
//div.className = "age";
li.appendChild(a);
li.appendChild(div);
container.appendChild(li);
}
}
which results this following error :
AssertionError: expected '<a class="name"></a>' to equal '<a class="name">John Doe</a>'
It appears contents of <a class="name"> is missing.
been working on this for the past 4 hours and don't seem to figure it out
Your code seems working in snippet. Just added the printRole method.
function printRole(usr) {
console.log('Clicked on user: ', `${usr.firstName} ${usr.lastName}`, '; Role is ', usr.role);
}
function findRoles(array) {
const container = document.getElementById('container');
for (let i = 0; i < array.length; i++) {
const li = document.createElement('li'),
a = document.createElement('a'),
div = document.createElement('div');
ul = document.createElement('ul');
let user = array[i];
a.innerText = user.firstName + ' ' + user.lastName;
a.className = 'name';
a.addEventListener("click", () => printRole(user))
//div.className = "age";
li.appendChild(a);
li.appendChild(div);
container.appendChild(li);
}
}
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
findRoles(names)
<div id="container"> </div>
I had to completely change the logic of your js code.
Was it necessary?
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
let name_mans = document.querySelectorAll('.name');
Array.from(name_mans).forEach(function(name_man, i) {
name_man.addEventListener('click', function() {
console.log(names[i].role);
});
});
<ul id="container">
<li>
<a class="name">John Doe</a>
<div class="age">41</div>
</li>
<li>
<a class="name">Mary Jane</a>
<div class="age">20</div>
</li>
</ul>
Related
I want the car properties to be printed for the li tag on the page. I mean to show name and other properties like a list.
let car = {
name: "benz",
type: "mercedes",
price: 5000
}
var propertyName = ['name', 'type', 'price'];
let ulCreate = document.createElement('ul');
document.body.appendChild(ulCreate);
for (var prop in propertyName) {
var li = document.createElement('li');
li.innerHTML = propertyName[prop] + " :" + car[propertyName[prop]];
ulCreate.appendChild(li);
}
<body>
<div>
<ul id="carr">
</ul>
<br/><br/>
</div>
</body>
If I understood you correctly, then this should give you some idea.
const myCar = {
name: "benz",
type: "mercedes",
price: 5000,
};
function renderCar(car) {
const listElement = document.getElementById("carr");
listElement.innerHTML += `
<li>name: ${car.name}</li>
<li>type: ${car.type}</li>
<li>price: ${car.price}</li>
`
}
renderCar(myCar);
<body>
<div>
<ul id="carr"></ul>
<br /><br />
</div>
</body>
If we have multiple cars (an array of objects), we can also iterate over the array and display an <li> for every property of every member.
If you have a list of cars you can do something like this:
let cars = [{
name: "benz",
type: "mercedes",
price: 5000
},
{
name: "fiat",
type: "punto",
price: 6000
},
{
name: "bmw",
type: "i900",
price: 7000
},
{
name: "toyota",
type: "corola",
price: 8000
}
]
let carsList = document.getElementById("carr");
cars.forEach(function(car, index) {
let name = document.createElement("li");
let type = document.createElement("li");
let price = document.createElement("li");
name.appendChild(document.createTextNode("Name: " + car.name));
type.appendChild(document.createTextNode("Type: " + car.type));
price.appendChild(document.createTextNode("Price: " + car.price));
carsList.appendChild(name);
carsList.appendChild(type);
carsList.appendChild(price);
})
<body>
<div>
<ul id="carr"></ul>
<br /><br />
</div>
</body>
You can apply it as follows.
You can create javascript in html and place property on objects.
let car = {
name: "benz",
type: "mercedes",
price: 5000
}
var propertyName = ['name', 'type', 'price'];
let ulCreate = document.createElement('ul');
document.body.appendChild(ulCreate);
for (var prop in propertyName) {
var li = document.createElement('li');
li.innerHTML = propertyName[prop] + " :" + car[propertyName[prop]];
ulCreate.appendChild(li);
}
let car = [{
name: "benz",
type: "mercedes",
price: 5000
},{
name: "A3",
type: "audi",
price: 8000
},{
name: "focus",
type: "ford",
price: 2500
}]
var propertyName = ['name', 'type', 'price'];
let ulCreate = document.createElement('ul');
document.body.appendChild(ulCreate);
for (var cr in car) {
for (var prop in propertyName) {
var li = document.createElement('li');
li.innerHTML = propertyName[prop] + ":" + car[cr][propertyName[prop]]
ulCreate.appendChild(li);
}
}
I am trying to create a page to add a new user when click into a value on menu bar like an Add option that allows users to input a name, an office number, and a phone number
Here is my code:
let menu = ["View", "Add", "Verify", "Update", "Delete"];
let list = document.getElementById("menuList");
menu.forEach((item) => {
let li = document.createElement("li");
li.innerText = item;
list.appendChild(li);
});
let users = [
{ name: "Jan", id: "1", number: "111-111-111" },
{ name: "Juan", id: "2", number: "222-222-222" },
{ name: "Margie", id: "3", number: "333-333-333" },
{ name: "Sara", id: "4", number: "444-444-444" },
{ name: "Tyrell", id: "5", number: "555-555-555" },
];
var div = "<div class='infor'>";
for (var i = 0; i < users.length; i++) {
div += "<div class='user-informations'>";
div += "<p>" + users[i].name + "</p>";
div += "<p>" + users[i].id + "</p>";
div += "<p>" + users[i].number + "</p>";
div += "</div>";
}
div += "</div>";
document.getElementById("usersList").innerHTML = div;
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</ul>
</div>
<div class="users" id="usersList">
</div>
</div>
my project:
Paying no attention to style or good software engineering practices:
let usersList = document.getElementById("usersList"),
addPage = document.getElementById("addPage");
const users = [
{ name: "Jan", id: "1", number: "111-111-111" },
{ name: "Juan", id: "2", number: "222-222-222" },
{ name: "Margie", id: "3", number: "333-333-333" },
{ name: "Sara", id: "4", number: "444-444-444" },
{ name: "Tyrell", id: "5", number: "555-555-555" },
];
function showUsers() {
usersList.innerHTML = "";
usersList.style.display = "inline";
addPage.style.display = "none";
users.forEach(u => {
const newUser = document.createElement("p");
newUser.innerHTML = `${u.id} ${u.name}<br/>${u.number}`;
usersList.appendChild(newUser);
})
}
function addOn() {
usersList.style.display = "none";
addPage.style.display = "inline";
}
function addUser() {
const id = document.getElementById("id").value;
const name = document.getElementById("name").value;
const number = document.getElementById("number").value;
users.unshift({ name: name, id: id, number: number});
showUsers();
}
showUsers();
.navbar { vertical-align: top; padding-right: 1rem; border-right:solid 1px red }
<div class="contact-container">
<table>
<tr>
<td class="navbar">
<ul id="menuList" style="cursor:pointer">
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png" />
<li onclick="showUsers()">View</li>
<li onclick="addOn()">Add</li>
<li>...</li>
</ul>
</td>
<td>
<div class="users" id="usersList"></div>
<div id="addPage" style="display:none">
Id: <input id="id" size="1"/> Name: <input id="name" /><br/>
Number: <input id="number" /><br/>
<button onclick="addUser()">Add</button>
</div>
</td>
</tr>
</table>
</div>
It is not necessary to generate the menu list dynamically unless the menu is really dynamic.
Ask if you need explanation on any of the stuff above.
okay so, I need to create a new div using jquery with the information of a first and last name that I loop from my array.. This is what I have so far, I was wondering if I could get some help on how to make it show up on my webpage. it needs to show up like:
hello firstname lastname
hello firstname lastname
hello firstname lastname
<div id="output"></div>
function names() {
var firstAndLast = [
{name: "jane", surname: "doe"},
{name: "john", surname: "leg"},
{name: "hunny", surname: "bun"}
];
var div = $("#output");
for (var i=0; i < firstAndLast.length; i++) {
}
var div1 = $("<div>").html("Hello name surname");
$("#names").append(div1);
Your code is almost there. The main issue is that you need to put the line of jQuery which creates the div and appends it within the for loop. In addition you can retrieve the name and surname from the objects in the array using the i variable to access them by index:
var $output = $("#output");
for (var i = 0; i < firstAndLast.length; i++) {
var div1 = $("<div>").html(`Hello ${firstAndLast[i].name} ${firstAndLast[i].surname}`);
$output.append(div1);
}
That being said, the most performant way to do this would be to use map() to build an array of HTML strings which you only append to the DOM once:
function names() {
let firstAndLast = [
{ name: "jane", surname: "doe" },
{ name: "john", surname: "leg" },
{ name: "hunny", surname: "bun" }
];
let html = firstAndLast.map(o => `<div>Hello ${o.name} ${o.surname}</div>`);
$("#output").append(html);
}
names();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
You can try something like this
function names() {
var firstAndLast = [{
name: "jane",
surname: "doe"
},
{
name: "john",
surname: "leg"
},
{
name: "hunny",
surname: "bun"
}
];
let _data = firstAndLast.reduce((acc, {
name,
surname
}) => {
acc += `hello <span>${name}</span> <span>${surname}</span><br>`
return acc;
}, "")
$("#output").html(_data);
}
names()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i=0 ;i<10;i++){
contacts[i] = [];
for(c=0;c<3;c++){
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
}
the code gives me the contacts array with 10 arrays and each array has the information repeated 3times
You don't need the second for loop:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [];
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
Or you can also use this way:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [FirstName, LastName, Adress];
}
I am not sure on the objective but I think you should be using objects to store your information instead of 2D arrays.
(Jsfiddle that show 2d array and array with objects). So instead of
var contacts = [
['John', 'Doe', '100 Main Street'],
['Jane','Smith','101 Main']
];
you would have
var contacts = [
{
first_name: 'John',
last_name: 'Doe',
address: '100 Main Street'
},
{
first_name: 'Jane',
last_name: 'Smith',
address: '101 Main Street'
}
];
Try this. It will push the form name and email onto the contacts
<form onsubmit='formSubmit(event);'>
<label>name</label>
<input id='name' value='John'/>
<label>email</label>
<input id='email' value='fake#test.com'/>
<br/>
<button>
add name and email
</button>
</form>
function formSubmit(event){
event.preventDefault();
contacts.push({
name: document.getElementById('name').value,
email: document.getElementById('email').value
})
console.log(contacts);
}
i have been given this code and told to add in the setup method to add the 4 fish owners.
Controller.prototype.setup = function () {
'use strict';
var theAquarium;
theAquarium = new Aquarium();
i have to add the following information
to add for each owner:
PHK Phil Key 8/05/1980
RUT Russel Turia 16/02/1984
TAN Tariana Norman 30/11/1987
JOG John Goff 12/12/1982
i tried adding it like this but it isn't working
Controller.prototype.setup = function () {
'use strict';
var theAquarium;
theAquarium = new Aquarium();
theAquarium.addFishOwner( 'PHK' , 'Phil' , 'Key' , setFullYear(8/05/1980));
theAquarium.addFishOwner( 'RUT' , 'Russel' , 'Turia' , setFullYear(16/02/1984));
theAquarium.addFishOwner( 'TAN' , 'Tariana' , 'Norman' , setFullYear(30/11/1987));
theAquarium.addFishOwner( 'JOG' , 'John' , 'Goff' , setFullYear(12/12/1982));
please help
Try this, let me know if I understand what you are asking
$(document).ready(function() {
var fisherman1 = {
name: "John",
lastName: "Doe",
DOB: '8/05/1980'
};
var fisherman2 = {
name: "John1",
lastName: "Al",
DOB: '8/05/1980'
};
var fisherman3 = {
name: "Alan",
lastName: "123",
DOB: '8/05/1980'
};
var fisherman4 = {
name: "Jim",
lastName: "A",
DOB: '8/05/1980'
};
var array1 = new Array(4);
array1.push(fisherman1);
array1.push(fisherman2);
array1.push(fisherman3);
array1.push(fisherman4);
for (x = 0; x < array1.length; x++) {
$("div").append(x + ":" + array1.pop(0).name + ".");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d"></div>