Name not printing

2

What I wanted was to get the name of the person shown with the alert but I'm not able to

My html code

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

2 answers

5

It was just necessary to add () to onclick to call the function and put the variable inside the function scope so that the name is captured during execution.

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

You have two problems with your code:

1) To call a function JavaScript you have to set () and preferably put ; at the end too.

2) You are taking the value of input id1 out of the function, ie, it was caught before executing the function. If it kept out the value printed on 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>
    
02.10.2018 / 22:13