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?
The reason you function doesn’t work when
lolis defined outside it, is because the DOM isn’t loaded yet when the JavaScript is first run. Because of that,getElementByIdwill returnnull(see MDN).You’ve already found the most obvious solution: by calling
getElementByIdinside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.There are a few other solutions. One is to wait until the entire document is loaded, like this:
Note the
onloadattribute of the<body>tag. (On a side note: thelanguageattribute of the<script>tag is deprecated. Don’t use it.)There is, however, a problem with
onload: it waits until everything (including images, etc.) is loaded.The other option is to wait until the DOM is ready (which is usually much earlier than
onload). This can be done with “plain” JavaScript, but it’s much easier to use a DOM library like jQuery.For example:
jQuery’s .ready() takes a function as an argument. The function will be run as soon as the DOM is ready. This second example also uses .click() to bind kk’s
onclickhandler, instead of doing that inline in the HTML.