Your code has a lot of structural error.First, on that line:var pessoa1 = new pessoa(document.getElementById('nome'));
You are assigning the returned element by getElementById the property nome, class pessoa, and not the value of the element.The correct would be document.getElementById('nome').value.But there's another problem: If you want to update the value whenever you click on mostrar, then you should make the creation of the instance of pessoa when mostrar be called.If you set this out of the function, as you did, the captured value would be just what you initially set.So I modified your code, so I left it like this:<form>
Qual é o seu nome? <input type="text" id="nome"><br><br>
<button id="btn-enviar" onclick="mostrar(event)">ENVIAR</button>
</form>
<p id="texto">
</p>
<script type="text/javascript">
/**
para classes, use letra maiúsculas
*/
function Pessoa(nome){
this.nome = nome;
}
var pessoa1;
function mostrar(event){
event.preventDefault();
pessoa1 = new Pessoa(document.getElementById('nome').value);
console.log(pessoa1);
document.getElementById('texto').innerHTML = pessoa1.nome;
}
</script>Note that besides all, I had to use the event.preventDefault()therefore form I would have a submit sent. preventDefault() prevents the standard action of the element.Tips:If you will only use Javascript events, you don't need to use the tag form. A form with a button inside, without specifying type, will make the browser understand that you want to submit the form. If you click on it, the page would probably be updated. So I used it preventDefault inside the form, but without the form nor would it be necessary.Avoid using onclick to call functions. This usually leaves the code more difficult to maintain. I would recommend the use of addEventListener.Example: function mostrar(e) {
e.preventDefault();
// resto do código
}
document.getElementById('nome').addEventListener('click', mostrar);
See examples https://developer.mozilla.org/pt-BR/docs/Web/API/Element/addEventListener .If pessoa is a simple object, because not using a Object of Javascript itself?Perhaps, in your case, it was only necessary to do this:var pessoa = {nome: null}
In the end, I would leave it like this:var elTexto = document.querySelector('#texto');
var elNome = document.querySelector('#nome');
var pessoa = {nome: null};
document.querySelector('#botao').addEventListener('click', function (e) {
e.preventDefault();
pessoa.nome = elNome.value;
elTexto.innerHTML = elNome.value;
console.log(pessoa);
})Qual é seu nome?
<input type="text" id="nome" />
<button id="botao">Enviar</button>
<p id="texto"></p>