Your code has a lot of structural error.
First, in this line:
var pessoa1 = new pessoa(document.getElementById('nome'));
You are assigning the element returned by getElementById
to the property nome
, of class pessoa
, not the value of the element.
The correct one 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 create the instance of pessoa
when mostrar
is called.
If you set this out of the function, as you did, the captured value would be only what you initially set.
So, I modified your code, 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, in addition, I had to use event.preventDefault()
because form
would cause a submit to be sent. preventDefault()
prevents the default action of the element.
Tips:
-
If you are going to use Javascript events only, you do not need to use the form
tag. A form with a button inside, without specifying the 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 preventDefault
inside the form, but without form
it would not even be necessary.
-
Avoid using onclick
to call functions. This often leaves the code more difficult to maintain. I would recommend using addEventListener
.
Example:
function mostrar(e) {
e.preventDefault();
// resto do código
}
document.getElementById('nome').addEventListener('click', mostrar);
See some examples here .
- If
pessoa
is a simple object, why not use a Object
of Javascript itself?
Maybe, in your case, you just have 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>