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?
Edit:
as your lol is local variable now, its good practice to use var keyword for declaring any variables.
this may work for you :
The reason you function doesn't work when
lol
is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run. Because of that,getElementById
will returnnull
(see MDN).You've already found the most obvious solution: by calling
getElementById
inside 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
onload
attribute of the<body>
tag. (On a side note: thelanguage
attribute 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
onclick
handler, instead of doing that inline in the HTML.Notice that this line:
is before the actual
<input>
element on your markup:Your code is parsed line by line, and the
lol = ...
line is evaluated before the browser knows about the existance of an input with idlolz
. Thus,document.getElementById('lolz')
will returnnull
, anddocument.getElementById('lolz').value
should cause an error.Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use
var
as others suggested, to avoid making it a global variable:You can also move the script to the end of the page. Moving all script blocks to the end of your HTML
<body>
is the standard practice today to avoid this kind of reference problem. It also tends to speed up page load, since scripts that take long to load and parse are processed after the HTML has been (mostly) displayed.document.getElementById('id').value