Your code has too much structural error.
First, on this line:
var pessoa1 = new pessoa(document.getElementById('nome'));
You are assigning the element returned by getElementById
to the property nome
, class pessoa
, and not the value of the element.
The right thing would be document.getElementById('nome').value
.
But there is another problem: If you want to update the value whenever it is clicked on mostrar
, then you should create the instance of pessoa
when mostrar
were called.
If you set this outside the function, as you did, the captured value would be just what you initially set.
So I modified his code, left him 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 on top of everything, I had to use the event.preventDefault()
, for the form
would cause a Ubmit to be sent. preventDefault()
prevents the standard action of the element.
Tips:
If you will only use Javascript events, you do not need to use the tag form
. 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. That’s why I used the preventDefault
within the form, but without the form
nor would it be necessary.
Avoid using onclick
to call functions. This usually makes code harder to maintain. I would recommend using addEventListener
.
Example:
function mostrar(e) {
e.preventDefault();
// resto do código
}
document.getElementById('nome').addEventListener('click', mostrar);
Here are some examples here.
- If
pessoa
is a simple object, why not use a Object
of Javascript itself?
Perhaps, in your case, it was only necessary to do this:
var pessoa = {nome: null}
In the end, I’d leave it at that:
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>
Maybe the event
onsubmit
form help you with this task. w3schools– Icaro Martins