javascript document element by id - javascript

If I need to see my out put in the page not in console.log i want use document get Element By Id how can i do that? he gave me just one result, Steve only !!
[Code: ]
http://i.stack.imgur.com/ISqzT.png
<script>
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['Microsoft Way']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobes",
number: "(444) 111 000",
address: ["Apple way"]
};
var list = function(obj) {
for( var key in obj){
console.log(obj);
document.getElementById("demo").innerHTML = key + "<br>";
}
}
var search = function(name) {
for(var key in friends){
if(name === friends[key].firstName){
console.log(friends[key]);
}
}
}
list(friends);
// search("Steve");
</script>

Hey the only change you have to make is using += instead of just = for the innerHTML function. Here you go:
text.innerHTML+=friend + "";

Simply append the result to your innerHTML, do not overwrite it, likewise:
document.getElementById("demo").innerHTML += key + "<br>";

Related

Using a for loop to display an array

I am new to arrays, and I have been trouble with making a for loop work with an array. What do I need to do?
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
for (i = 0; 1 < arrPeople.length; i++) {
text += (arrPeople[i] + '<br />');
}
}
There were a couple of minor errors in your function. The for loop statement is three parts: variable initialization, a condition that's checked after each loop, and an action that's performed after each loop. You had mistyped your condition as 1 < arrPeople.length which would always be true. Also you weren't returning a value from the function to be used by the calling code.
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
for (var i = 0; i < arrPeople.length; i++) {
text += (arrPeople[i] + '<br />');
}
return text;
}
pick your poison ...
you can also use array.foreach ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
arrPeople.forEach(function(person) {
text += person + '<br />';
});
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
here's an possibly an even simpler solution using array.join ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = arrPeople.join("<br />");
text += "<br />";
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
or if you prefer, you can also use the functional style using array.reduce ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = arrPeople.reduce(function(txt, itm) {
return txt + '<br />' + itm;
})
text += "<br />";
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Looks like you just want to display the list of names in the array vertically. You can do it without for-loop.
function start() {
var text = [ 'Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher' ].join( '<br />' );
}
You can use join to concatenate each array item and you can specify a separator for each. This way there is no extra <br/>. see array.join

Converting Javascript array objects to uppercase

var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
}
How do I convert contacts array to uppercase? After converting the array to uppercase, I want to display the full name in alphabetical order as shown in the picture. Or is there any other way to accomplish without converting to uppercase?
You can use this to convert a string to title casing:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
See example usage:
var nameMixedCaseing = ["alan bong" , "JusTin weasel", "Tom curry"]
for (i = 0; i < nameMixedCaseing.length; i++)
console.log(toTitleCase(nameMixedCaseing[i]));
Result is:
Alan Bong
Justin Weasel
Tom Curry
So in your code you can call this function before saving the person object
person.firstName = toTitleCase(person.firstName);
person.lastName = toTitleCase(person.lastName);
contacts.push(person);
You can use a combination of functions, one to capitalize, one to sort each time a new contact is pushed into the array:
var contacts = [
{
fname: 'andrew',
lname: 'mCGonahan'
},
{
fname: 'paUla',
lname: 'Ptrokva'
},
{
fname: 'kevin',
lname: 'harGRove'
},
{
fname: 'CAmille',
lname: 'dUpoIs'
},
{
fname: 'AlbERt',
lname: 'sWanson'
}
];
function capitalize(arr) {
for (var i = 0; i < arr.length; i++) {
var first = arr[i].fname;
var last = arr[i].lname;
arr[i].fname = first.slice(0,1).toUpperCase() + first.slice(1).toLowerCase();
arr[i].lname = last.slice(0,1).toUpperCase() +last.slice(1).toLowerCase();
}
return arr;
}
function sortByLast(arr) {
return arr.sort(function(a, b) {
if (a.lname > b.lname) return 1;
if (b.lname > a.lname) return -1;
return 0;
});
}
//you can call the following after you have pushed the newest contact into the array
// or you could capitalize the inputs as they are entered, then run the sort function on the contacts array
contacts = sortByLast(capitalize(contacts));
document.getElementById('sortedContacts').innerHTML = JSON.stringify(contacts);
<div id="sortedContacts"><h3></h3></div>

Javascript codecademy 5.5 function doesn't return correct data

Thanks for having a look at my question! I'm trying to complete the JavaScript course in codecademy and this has me stumped. I can't even find help in the codecademy forums. I am trying to figure out why "Bob Jones" isn't logged to the console. Any help is greatly appreciated. Here is my code:
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones#example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson#example.com"
};
var contacts = [bob, mary];
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
};
function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
};
/*Create a search function
then call it passing "Jones"*/
function search(lastName){
var contactsLength = contacts.Length;
for(var i = 0; i<contactsLength; i++){
if(lastName === contacts[i].lastName){
printPerson(contacts[i]);
}
}
};
search("Jones");
The problem is that JavaScript is case sensitive and the array length is available under the lengthproperty, not Length.
P.S. learn to use a debugger.

Object comparison help needed

I would like to compare the names, if they match, then say we have similar names, else that we have different names. But this code gives output undefined while comparing names.
Could someone please help me out to understand/fix this problem?
I want to get following, for example:
We have different names, Bob and I.
function addPersonMethods(obj){
this.obj = obj;
}
addPersonMethods.prototype.greet = function(str){
return str + ", my name is "+ this.obj.name;
}
addPersonMethods.prototype.nameshake = function(othername){
this.othername = othername;
if (this.obj.name == this.othername){
console.log("We have the same name ," + this.obj.name + " and I! ");
}
else
console.log("We have different names ," + this.obj.name + " and I.");
}
var bob_def = { name: 'Bob', age: 21 };
var eve_def = { name: 'Eve', age: 21 };
var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({name:'Bob', age: 40});
console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));
console.log(bob.nameshake(eve));
Your nameshake() method expects a string (the name), but you're passing an object, so the comparison will never be true. You want to compare to that object's .obj.name.
Second, you're logging the result of bob.nameshake(), when the function doesn't actually return anything.
And you're printing your own name in the "We have..." statements, when you want to print the other person's.
function addPersonMethods(obj) {
this.obj = obj;
}
addPersonMethods.prototype.greet = function(str) {
return str + ", my name is " + this.obj.name;
}
addPersonMethods.prototype.nameshake = function(otherperson) {
var othername = otherperson.obj.name;
if (this.obj.name == othername) {
console.log("We have the same name, " + othername + " and I! ");
}
else
console.log("We have different names, " + othername + " and I.");
}
var bob_def = {
name: 'Bob',
age: 21
};
var eve_def = {
name: 'Eve',
age: 21
};
var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({
name: 'Bob',
age: 40
});
console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));
bob.nameshake(eve);
bob.nameshake(another_bob);
You are comparing a string (this.obj.name) to an object (othername). They won't be equal so you will always output that they have different names. The return value of any function by default is undefined unless you specify otherwise, so that's why your output is tailed by undefined.
Either pass in eve.obj.name to the function, or extract that value inside the function so you can compare properly.

angular building an array with a for loop

I'm building an array dynamically in a test angular app. Basically I have a scope function that generates an array of people and returns the array and I have an ng-repeat on the array. The array is not displaying but I'm not getting any errors in the console either, so idk what's up:
am I calling the getPerson function correctly? If there's a better way to do this do let me know.
heres the fiddle as well
$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};
$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
I've updated your fiddle here : https://jsfiddle.net/7j2khgbj/2/
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
};
Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};
var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';
};
$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();
/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});
Some problems I saw:
1) $scope.people was a function, not an array (so I simply executed it and saved the result)
2) you were always overwriting the person (you need a Person class that creates new instances for the array element, not overwrite the same instance with new data - that way you'll get the same thing in all the array elements)
3) on $scope you should put things that need to be accessible from the view. Helper functions can just be local in the controller (if you don't want them as services, although as services they are reusable)
4) track by on ng-repeat (in case of duplicate keys)

Categories