Problem retrieving information from the page and submitting it to the JavaScript object constructor

I wanted to create a simple form on the page with a few inputs and button and by receiving information from the inputs. I try to put the person’s information on the screen, but the web page does not display the information well, but only shows [object Object].

function structur() {
  function person(name, family, age) {
    this.name = name;
    this.family = family;
    this.age = age;
  }
  var name1 = document.getElementById('iname').value;
  var family1 = document.getElementById('ifamily').value;
  var age1 = document.getElementById('iage').value;
  var demo = new person(name1, family1, age1)
  document.getElementById('result').innerHTML = demo;
}
<p id="result">show result here! </p>
<button id="show" onclick="structur()">click to show</button>
<input type="text" id="iname" placeholder="name:">
<input type="text" id="ifamily" placeholder="family:">
<input type="number" id="iage" placeholder="age:">

Answer

demo is basically a Object, which you are trying to insert in html, therefore you first have to convert it into String so that it can be parsed into HTML DOM.

function structur (){
function person(name, family, age){
      this.name = name;
      this.family = family;
      this.age = age;
}
var name1 = document.getElementById('iname').value;
var family1 = document.getElementById('ifamily').value;
var age1 = document.getElementById('iage').value;
var demo = new person (name1,family1,age1)
document.getElementById('result').innerHTML= JSON.stringify(demo);
}

Few Tips:

  • Use PascalCase naming convention for Object Constructor function, it totally depends on you to follow this or not, because it make more understandable code for other developers that this is a Object Constructor.
  • Make as less side effects as you can, like in structur, your function is depending on value which is not in scope of person function.

Example:

function Person(name, family, age){
      this.name = name;
      this.family = family;
      this.age = age;
}
function structur(){
    var name1 = document.getElementById('iname').value;
    var family1 = document.getElementById('ifamily').value;
    var age1 = document.getElementById('iage').value;
    var demo = new Person (name1,family1,age1)
    document.getElementById('result').innerHTML= JSON.stringify(demo);

}