Name not printing

Asked

Viewed 62 times

2

What I wanted was to get the name of the person shows with Alert but I’m not getting

My html code

var nome = document.getElementById('id1').value;
function clique(){
  alert(nome);
}
<input id="id1" type="text"/>
<button onclick="clique">Clique aqui</button>

2 answers

5


Just needed to add () in the onclick to call the function and place the variable within the function scope so that the name is captured during the execution of the function.

function clique(){
  var nome = document.getElementById('id1').value;
  alert(nome);
}
<input id="id1" type="text"/>
<button onclick="clique()">Clique aqui</button>

  • our missing attention, thank you very much

4

You have two problems with your code:

1) To call a function JavaScript have to put the () and preferably place the ; in the end too.

2) You are taking the value of input id1 out of the function, i.e., it was picked up before performing the function. If it kept out the value printed in the alert would always be empty.

function clique(){
  var nome = document.getElementById('id1').value;
  alert(nome);
}
<input id="id1" type="text"/>
<button onclick="clique();">Clique aqui</button>

  • Sorry if I’m boring, but why put ; in the end rs?

  • The ; is a line delimiter. If there is only 1 line, there is no need for rs

  • @sam, I’ve seen many codes running multiple methods in the same event, for example pegaValor();exibeValor();, because of this I always maintain ; to avoid problems.

  • Sure, but in this case you don’t need :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.