How go get an input text value in JavaScript?
<script language="javascript" type="text/javascript">
lol = document.getElementById('lolz').value;
function kk(){
alert(lol);
}
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" OnClick="kk()"/>
</body>
When I put lol = document.getElementById('lolz').value;
outside of the function kk()
, like shown above, it doesn't work, but when I put it inside, it works. Can anyone tell me why?
use this
Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:
If you insist
var lol
to be set outside the function kk, then I propose this solution:Note that the
script
element must follow theinput
element it refers to, because elements are only queryable withgetElementById
if they already have been parsed and created.Both examples work, tested in jsfiddler.
Edit: I removed the
language="javascript"
attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:and
All the above solutions are useful. And they used the line
lol = document.getElementById('lolz').value;
inside the functionfunction kk()
.What I suggest is, you may call that variable from another function
fun_inside()
It can be useful when you built complex projects.
The reason that this doesn't work is because the variable doesn't change with the textbox. When it initially runs the code it gets the value of the textbox, but afterwards it isn't ever called again. However, when you define the variable in the function, every time that you call the function the variable updates. Then it alerts the variable which is now equal to the textbox's input.