Storing info in an array(firstName, lastName, accNumber, etc). I already have some data in array. I want to ask user input and push that input in array and save it as well as display it on screen(not in console). Also new info is not saving in the array. I use prompt as well as form . from is not working.
/* creatting array */
var customer = [
{fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
{fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
{fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];
console.log(customer.length);
console.log(customer[1].fname);
console.log(customer[2].lname);
var newName = prompt("what is your lnamename?");
customer.push(newName);
console.log(customer);
/*function to add data in array*/
function addInArray() {
var addName = document.getElementById("#nameInput");
customer.push(addName.value);
addName.value = "";
console.log(customer);
}
/* display array*/
function displayArray(){
for(var i=0; i < customer.lenght; i++){
document.write("customer" + i + customer[i] + "</br>");
document.getElementById("#showName").innerHTML = customer[i];
}
}
</script>
<form>
<input id="nameInput" type="text"/ placeholder="yourInfo">
<button type="button" id="add" onclick="addInArray();">Add </button>
<button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div>
</body>
You shouldn't write # while you are using getElementById
/* creatting array */
var customer = [
{fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
{fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
{fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];
displayMyAcc()
function displayMyAcc(){
var myAccNo = prompt("what is your acc number?");
document.getElementById("showName").innerHTML=JSON.stringify(customer.filter(x=>x.accNo==myAccNo)[0]);
}
/*function to add data in array*/
function addInArray() {
var addName = document.getElementById("nameInput");
customer.push(addName.value);
addName.value = "";
}
/* display array*/
function displayArray(){
for(var i=0; i < customer.length; i++){
document.getElementById("showName").innerHTML += JSON.stringify(customer[i]);
}
}
<form>
<input id="nameInput" type="text"/ placeholder="yourInfo">
<button type="button" id="add" onclick="addInArray();">Add </button>
<button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div>
Related
I am trying to filter an array which it should works as follow.
I have users and I have pages role.
In the pages role I have the user_id and the role.
I need to check if user_id exist in one page then don't show it to the users array anymore.
If user_id doesn't exist then it will be shown at the search array of users.
When I try to console.log the users and the pages.role I am getting like this.
For pages.role
pages {role: "Moderator", userID: "5fbc1bc72ffec245c4bd7725"}
pages {role: "Editor", userID: "5eacb3617977572bb34bfc89"}
pages {role: "Analyst", userID: "602e435fd201a0092d791b36"}
And for the users.
0: {_id: "5eacb3617977572bb34bfc89", firstName: "test", email: "test.test#outlook.com", lastName: "test", password: "$2b$10$UEM0xsB/tJQJ8xQKhuZXDOIZ/K26bSje28zPOvEAjrOWQqciEY7s.", …}
1: {_id: "5fbc1bc72ffec245c4bd7725", firstName: "test", email: "test.test#test.de", lastName: "test", password: "$2b$10$iynDhvHHYs4SCFOXwdccBOvYnqUxjS.SihLAF5ugO9gQQbnNESjU.", …}
2: {_id: "602e433bd201a0092d791b05", firstName: "Smart", email: "smart#smart.com", lastName: "test", password: "$2b$10$fJ4Uqx0DILQUzrPDKiVpnOYqhdbqEYH1vZVnR5HMNOYO4yyNUWcKa", …}
3: {_id: "602e435fd201a0092d791b36", firstName: "al", email: "t#t.com", lastName: "al", password: "$2b$10$joZSBS9uwEmCi2L3G2CtZ.JuSIIpBpL/2iPe3LCQ/YpXyVQOL1jpu", …}
4: {_id: "602e4c30e3346466703376ab", firstName: "BL", email: "bl#outlook.com", lastName: "br", password: "$2b$10$R.s.X1ezymXgH0XVnWfW/etIiRqeHjsl6HfQi00pudvWS6dGxIErG", …}
length: 5
This is my code in TS.
public page: Page;
public name;
public users: User[] = [];
public searchUsers: User[] = [];
public search = "";
public role = new Roles();
public userID;
public privacies = [
{ id: Role.Admin, name: "role.admin" },
{ id: Role.Editor, name: "role.editor" },
{ id: Role.Moderator, name: "role.moderator" },
{ id: Role.Advertiser, name: "role.advertiser" },
{ id: Role.Analyst, name: "role.analyst" },
];
this.receiver.dataUpdate$.subscribe((success: any) => {
this.page = success;
if (this.page.pageUrl) {
this.name = this.page.pageUrl;
} else {
this.name = this.page._id;
}
this.userService.getUsers();
this.userService.userModel().subscribe(res => {
this.users = res;
let id;
this.page.roles.map(t => {
id = t.userID
})
console.log(this.users);
const userFilter = this.users.filter(user => user._id !== id);
this.searchUsers.push(...userFilter);
//Here it filter only the last value that is added as page role
})
And this is my code in HTML.
<input class="form-control-sm col-md-6" [(ngModel)]="search" type="text" placeholder="Type name or email" >
<select
name="selectedValue"
id="selectedValue"
[ngModel]="privacies"
(ngModelChange)="addRole($event)"
class="col-md-3 form-control-sm"
required
>
<option
*ngFor="let privacy of privacies"
[value]="privacy.id"
(change)="addRole(privacy)"
[selected]="privacy"
>
{{ privacy.name | translate}}
</option>
</select>
<button class="btn btn-primary col-md-3 btn-sm" (click)="saveUserRole()">Add</button>
</div>
<div *ngIf="search" class="card__search">
<div *ngFor="let f of (searchUsers | searchUser:search)" class="card__list">
<div class="d-flex row pr-2 pl-2 align-items-center" (click)="addUser(f)">
<img ngx-gravatar [email]="'example#mail.com'" fallback="mp" size="35">
<span class="pr-2 pl-2">
{{f.firstName}} {{f.lastName}}
<span>
</span>
</span>
</div>
</div>
</div>
</div>
let id;
this.page.roles.map(t => {
id = t.userID // the problem is here
})
console.log(this.users);
the problem is in this line id will be assigned the value of the last element's id in page.role.
to fix:
1- declare id as array:
const id:string[] = [];
2-push the ids in role.page:
this.page.roles.forEach(t => { //note here we are using forEach instead of map
id.push(t.userID)
})
3-filter the users:
const userFilter = this.users.filter(user => !id.includes(user._id));
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>
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>