You're getting undefined
for name
, age
, and state
within peron
because you're not passing person
anything when you click your button:
<button id="btn" onclick="person();">Add</button>
<!-- Where are the arguments? ---^ -->
(When calling person
that way, you'll also get back undefined
as the result of the call, since you haven't used new
and person
doesn't have a return x
statement. But I assume you mean the parameters, since you're not looking at the return value.)
Your JavaScript code showing you calling it elsewhere is correct (other than getting standard practices around capitalization in JavaScript names1):
var NewPerson = new person(name, age, state);
If you wrapped up all your JavaScript code (getting the values, calling new person
, etc.) into a new function, say createPerson
, and called that instead, it would largely work:
function createPerson() {
var name = document.getElementById('inputValueName').value;
var age = document.getElementById('inputValueAge').value;
var state = document.getElementById('inputValueState').value;
function person(name, age, state) {
this.name = name;
this.age = age;
this.age = age;
this.state = state;
}
var NewPerson = new person(name, age, state);
console.log(NewPerson);
}
<input type="text" id="inputValueName">
<input type="text" id="inputValueAge">
<input type="text" id="inputValueState">
<button id="btn" onclick="createPerson();">Add</button>
1 You're obviously free to do what you like in your own code, but overwhelmingly, the convention in JavaScript is that constructor functions (ones you call via new
) start with a capital letter, and basically no other variables do. So it would be Person
(not person
), for the constructor, and newPerson
(not NewPerson
) for the variable referencing the new person.
Side note: onxyz
-attribute-style event handlers are handy for quick-and-dirty mockups, but they have several problems, not least that the functions they call have to be globals, and globals are a Bad Thing™. Make sure you familiarize yourself with modern event handling for use in real apps, addEventListener
and the like.