My question is: How to migrate var x which is basically user input data to var person so user could change person.firstName by inputing data into <input type="text" id="userInput" value=""> element. I am very new for JS concepts, so I would be appreciate for any help. Thank you.
var person = {
firstName : "John",
lastName : "Doe",
age : 30,
fullName : function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName (); // Result: My name is John Doe I am 30 yers old
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = x;}
You can add the event input to your input field.
Set the entered input (firstName) to your object person.
Look this code snippet:
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName();
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
person.firstName = x;
document.getElementById("demo").innerHTML = person.fullName();
}
document.getElementById("userInput").addEventListener('input', myFunction);
<span id='demo'></span>
<p>User Input</p>
<input type="text" id="userInput" value="">
See? The object person is being updated automatically.
Resource
EventTarget.addEventListener()
Working with objects
Just do what you say:
function updateFirstName() {
person.firstName = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = person.fullName();
}
Related
I'm taking a javascript class in school and we just started OOPs. I'm struggling to understand how to return all of an object's properties to an HTML paragraph, division, etc.
Here's the code in question:
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.describeMyself = function(){
return document.getElementById("test").innerHTML = "My name is " + this.firstName;
}
}
var john = new Person("John", "Smith", 53, "male");
john.describeMyself();
This works to output the first name but I need to output ALL the values.
Thanks in advance for your help.
I'm struggling to understand how to return all of an object's properties to an HTML paragraph, division, etc.
To return all objects properties to the html, in a similar way you are doing, will be to include them on your this.describeMyself function or you can create a new function eg this.allProperties
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.describeMyself = function(){
return document.getElementById("test").innerHTML = "My name is " +
this.firstName;
}
// You can keep this function, modify it or modify your describe myself.
this.allProperties = function(){
return document.getElementById("test").innerHTML = "My name is " +
this.firstName + " " + this.lastName + "and I'm a "+ this.age +" year old " + this.gender;
}
}
var john = new Person("John", "Smith", 53, "male");
john.allProperties();
This would print in your #id tag:
My name is John Smith and I'm a 53 year old male.
You can modify the text so that it returns whatever you want but the idea is to create a function that returns document.getElementById("test").innerHTML and then you can add the properties that you want to return.
Just write a method for each. You are doing it right. I am assuming that you want to print something like:
My first name is this.firstName.
My last name is this.lastName.
My age is this.age.
In that case, a method for each will do the job.
Or alternatively, you can first get an array of all the properties by using Object.keys() method.
Then loop through that array.
Assuming your sentence structure is going to be the same each time:
"My " + propertyName + " is: " + propertyValue.
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
}
var john = new Person("John", "Smith", 53, "male");
var su = Object.keys(John);
for(var i = 0; i < su.length; i++) {
console.log(console.log("My " + su[i] + " is " + john[su[i]]))
}
I hope this helps.
Thank You
The properties on your Person will just be the keys on an Object, so if you want to write a function that will always output all properties you can use Object.keys() to iterate through your object's properties:
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.getAllProps = function() {
return Object.keys(this).reduce(function(p, n){
if (typeof this[n] === 'function') {
return p;
} else {
return p + this[n] + ', ';
}
}.bind(this), '');
},
this.describeMyself = function(){
return document.getElementById("test").innerHTML = this.getAllProps();
}
}
This is assuming you just want to output your property values only, with no sentence structure.
The code seems to work just fine.
You can simply keep using the + operator to continue putting together the string that will be output in the div.
Here's an example
A codepen demo
I hope this helps
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.describeMyself = function(){
return document.getElementById("test").innerHTML = "My name is " + firstName + " " + lastName +"." + " I am.....";
}
}
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.describeMyself = function(){
return document.getElementById("test").innerHTML = "My name is " + this.firstName + ", I'm a " + this.age + " year old " + this.gender + " StackOverflow leecher";
}
}
var john = new Person("John", "Smith", 53, "male");
john.describeMyself();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I will be adding a list of contacts and put them in a div based on first character of lname. If the div doesn't exists, it will be created dynamically. I'd want to display the contact information on clicking the name. In the following implementation, showMe( ) function not working to display the contact information .
<html>
<head>
<style>
.holder{
background-color:yellow;
margin-top:10px;
width: 300px;
}
.holder span{
background-color: Green;
height:20px;
color:white;
}
</style>
<script>
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 person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length-1]; //take the last pushed object from the array
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if(!document.getElementById(lastNameFirstChar + "_holder")){
document.getElementById("mydiv").innerHTML += "<div id='"+lastNameFirstChar+"_holder' class='holder'><span>"+lastNameFirstChar+"</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + currPerson.id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id) {
alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname+" "+person.lname+"</br> "+person.email+"</br>"+person.phone;
target.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
</head>
<body>
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
</body>
</html>
<script>
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 person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length - 1]; //take the last pushed object from the array
var id = contacts.length - 1;
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if (!document.getElementById(lastNameFirstChar + "_holder"))
{
document.getElementById("mydiv").innerHTML += "<div id='" + lastNameFirstChar + "_holder' class='holder'><span>" + lastNameFirstChar + "</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id)
{
//alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname + " " + person.lname + "</br> " + person.email + "</br>" + person.phone;
mydiv.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
When you call showMe() function you are supposed to send the id of the person by currPerson.id
but when you defined var person you didn't give it the id property.
you have this
var person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
make it like this
var person = {
id: contacts.length,// note this extra parameter
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
now when you call
"<span onclick='showMe(" + currPerson.id + ")'>"
currentPerson.id will not be undefined anymore.
Secondly when you call this line
target.innerHTML = "<div>" + contactInfo + "</div></br>";
you haven't defined the variable "target".
add this line before the above line
var target= document.getElementById("mydiv")
where "myDiv" is the id of what you defined in the html markup
<div id="mydiv">
How do I properly create a function within a function prototype?
What I have is this:
<body>
<p id="demo"></p><script>
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
person.prototype.name = function() {
return {
myFunc: function() {
this.firstName + " " + this.lastName;
}
}
};
var myFather = new person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.name().myFunc;
</script>
</body>
When I run this it returns "My father is function () { this.firstName + " " + this.lastName; }" , but I was expecting John Doe.
You need call function, add () to myFunc. In your example you added reference to internal function.
document.getElementById("demo").innerHTML = "My father is " + myFather.name().myFunc();
Also add return to myFunc. To get properties from parent scope - save reference to this
person.prototype.name = function () {
var _this = this;
return {
myFunc: function () {
return _this.firstName + " " + _this.lastName;
}
}
};
Example
Myfunc is a function. When you call it, call like myfunc()
You are not calling myFunc and also that function does not return anything. I find this cleaner and a better way to define the funciton prototype:
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype = {
name: function() {
return this.firstName + " " + this.lastName;
}
};
Note that name now returns return this.firstName + " " + this.lastName;.
Then simply:
document.getElementById("demo").innerHTML = "My father is " + myFather.name();
i'm trying to do a form that will allow the user to see the details that he put into the fields after he clicked the button. for some reason the javascript doesn't read the values of the text the user put into the form. any help?
<form>
first name:
<input type="text" autofocus autocomplete="on" placeholder="first name" required id="first">
last name:
<input type="text" autocomplete="on" placeholder="last name" required id="last">
year of birth:
<input type="number" pattern="^[0-9]{4}" id="year">
gender:
<select id="sel">
<option selected>MALE</option>
<option>FEMALE</option>
</select>
<button id="butt">click</button>
</form>
the javascript :
function cont(){
function person()
{
this.FirstName = null;
this.LastName = null;
this.YearOfBirth = null;
this.Gender = null;
this.Weight = null;
this.Height = null;
this.Country = null;
this.FullName = function()
{
return this.FirstName + " " + this.LastName
};
this.Age = function()
{
var today = new Date();
var yy = today.getFullYear();
return yy - this.YearOfBirth;
};
this.toString = function()
{
return "this rider lives in " + this.Country + " and his name is " + this.FirstName + " " + this.LastName;
};
}
var rider = new person
rider.FirstName = document.getElementById('first').value
rider.LastName = document.getElementById('last').value
rider.YearOfBirth = document.getElementById('year').value
rider.Gender = document.getElementById('sel').value
document.getElementById('butt').onclick = function()
{
if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
{
alert ("fill all the required fields")
}
else
{
document.write(rider.FirstName + "<br>")
document.write(rider.LastName + "<br>")
document.write(rider.YearOfBirth + "<br>")
document.write(rider.Gender + "<br>")
document.write(rider.FullName() + "<br>")
}
} }
You are setting the "rider." values when the page loads (and they are empty) but not getting them again when the user clicks the button. Thus, the document.write functions are just writing empty values. Try:
document.getElementById('butt').onclick = function()
{
rider.FirstName = document.getElementById('first').value;
rider.LastName = document.getElementById('last').value;
rider.YearOfBirth = document.getElementById('year').value;
rider.Gender = document.getElementById('sel').value;
if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
{
alert ("fill all the required fields");
}
else
{
document.write(rider.FirstName + "<br>");
document.write(rider.LastName + "<br>");
document.write(rider.YearOfBirth + "<br>");
document.write(rider.Gender + "<br>");
document.write(rider.FullName() + "<br>");
}
} }
I asked a question here:
Extending javascript literal object
which was solved because I forgot return. Now I didn't forget return and I got undefined again, why ?
<script>
var secretAgent = (function(){
var person = {},
firstName = "James",
lastName = "Bond";
person.WhoAreYou = function() {
alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
};
return person;
})();
</script>
<script>
secretAgent.WhoAreYou();
</script>
Update: why mine doesn't work whereas I think I did the same thing as the one below that works:
http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
//Revealing Module Pattern (Public & Private)
var skillet = (function() {
var pub = {},
//Private property
amountOfGrease = "1 Cup";
//Public property
pub.ingredient = "Bacon Strips";
//Public method
pub.fry = function() {
console.log( "Frying " + pub.ingredient );
};
//Private method
function privateWay() {
//Do something...
}
//Return just the public parts
return pub;
}());
//Public Properties
console.log( skillet.ingredient ); //Bacon Strips
//Public Methods
skillet.fry();
//Adding a public property to a Module
skillet.quantity = 12;
console.log( skillet.quantity ); //12
//Adding a public method to a Module
skillet.toString = function() {
console.log( skillet.quantity + " " +
skillet.ingredient + " & " +
amountOfGrease + " of Grease" );
};
try {
//Would have been successful,
//but can't access private variable
skillet.toString();
} catch( e ) {
console.log( e.message ); //amountOfGrease is not defined
}
You need to declare those properties on the literal itself (rather than separate unrelated variables), like this:
var secretAgent = (function(){
var person = { firstName: "James", lastName: "Bond" };
person.WhoAreYou = function() {
alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
};
return person;
})();
You can test it out here.
There are two problems here, as I see it.
You did forget the return, again. :-) The WhoAreYou function doesn't actually return anything, it just alerts. Hence secretAgent.WhoAreYou() returns undefined too.
The alert shows "My name is undefined, undefined undefined". This is because of the scope of the variables used. You assign the WhoAreYou to person, and within the body you reference this.lastName. The this here refers to the person variable, and as you can see this object does not have a lastName property.
There are two ways then that you can fix the latter issue. Firstly, by adding the name variables to the person object:
var secretAgent = (function(){
var person = {};
person.firstName = "James";
person.lastName = "Bond";
person.WhoAreYou = function() {
alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
};
return person;
}
)();
// Although the first three lines would be more natural as:
var person = { firstname: "James", lastName: "Bond" };
Secondly, you can instead choose to drop the this reference, which will instead refer to the local variables you just defined:
var secretAgent = (function(){
var person = {},
firstName = "James",
lastName = "Bond";
person.WhoAreYou = function() {
alert("My name is " + lastName + ", " + firstName + " " + lastName);
};
return person;
}
)();
You'll of course need to add appropriate returns to the WhoAreYou function in both examples.
Remove "this" from the variables since you are setting them as a var with in the anonymous function, using this points to that function and not "Person" which is where you are now calling them.
<script>
var secretAgent = (function(){
var person = {},
firstName = "James",
lastName = "Bond";
person.WhoAreYou = function() {
alert("My name is " + lastName + ", " + firstName + " " + lastName);
};
return person;
}
)();
</script>
<script>
secretAgent.WhoAreYou();
</script>
example here: JSFiddle
Why not just:
var secretAgent = {
firstName: "James",
lastName: "Bond",
whoAreYou: function() {
alert("My name is " + this.lastName + ", " +
this.firstName + " " + this.lastName);
}
};
The way you defined firstName and lastName are not fields to object person itself. But they are upper values to function WhoAreYou. So you could write the function like this:
person.WhoAreYou = function() {
alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
};
Its like if those were private variables to the function. The alternative is declaring as filelds to the object itself like this:
var person = {
firstName: "James",
lastName: "Bond",
};
The the method whould work as you wrote it.
The variable this is person in your case, also firstName and lastName are defined as local variables, but not as properties of the person, so you can just access them within the anonymous function by names:
var secretAgent = (function(){
var person = {},
firstName = "James",
lastName = "Bond";
person.WhoAreYou = function() {
alert("My name is " + lastName + ", " + firstName + " " +lastName);
};
return person;
})();
secretAgent.WhoAreYou();