How to get an input text value in JavaScript
Solution 1
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 return null
(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:
<script type="text/javascript">
var lolz;
function onload() {
lolz = document.getElementById('lolz');
}
function kk(){
alert(lolz.value);
}
</script>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" onclick="kk();"/>
</body>
Note the onload
attribute of the <body>
tag. (On a side note: the language
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:
<script type="text/javascript">
$(document).ready(function() {
var lolz = $('#lolz');
var kk = $('#kk');
kk.click(function() {
alert(lolz.val());
});
});
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" id="kk" />
</body>
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.
Solution 2
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:
<script type="text/javascript">
function kk(){
var lol = document.getElementById('lolz').value;
alert(lol);
}
</script>
If you insist var lol
to be set outside the function kk, then I propose this solution:
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" OnClick="kk()"/>
<script type="text/javascript">
var lol = document.getElementById('lolz');
function kk() {
alert(lol.value);
}
</script>
</body>
Note that the script
element must follow the input
element it refers to, because elements are only queryable with getElementById
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:
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
and
A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]
Solution 3
Notice that this line:
lol = document.getElementById('lolz').value;
is before the actual <input>
element on your markup:
<input type="text" name="enter" class="enter" value="" id="lolz"/>
Your code is parsed line by line, and the lol = ...
line is evaluated before the browser knows about the existance of an input with id lolz
. Thus, document.getElementById('lolz')
will return null
, and document.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:
function kk(){
var lol = document.getElementById('lolz').value;
alert(lol);
}
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.
Solution 4
Edit:
- Move your javascript to end of the page to make sure DOM (html elements) is loaded before accessing them (javascript to end for fast loading).
- Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
- Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
- To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
- Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Solution 5
How to get an input text value in JavaScript
var textbox;
function onload() {
//Get value.
textbox = document.getElementById('textbox');
}
function showMessage() {
//Show message in alert()
alert("The message is: " + textbox.value);
}
<body onload="onload();">
<div>
<input type="text" name="enter" class="enter" placeholder="Write something here!" value="It´s a wonderful day!" id="textbox"/>
<input type="button" value="Show this message!" onClick="showMessage()" />
</div>
Maria
Updated on March 26, 2021Comments
-
Maria about 3 years
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 functionkk()
, like shown above, it doesn't work, but when I put it inside, it works. Can anyone tell me why? -
Mauno Vähä almost 12 yearsit is also to be noted that javascript should be placed bottom of the page for fast loading, not before of the html like shown within examples above. Then it also recognizes given html elements.
-
Maria almost 12 yearsVERY CLEAR EXPLANATION, THANKS!
-
Mauno Vähä almost 12 yearssee bfavarettos answer and my comment for complete explanation, he was faster! :)
-
bfavaretto almost 12 yearsYes, that's one option. In terms of fast loading, it won't make much difference in this case.
-
Mauno Vähä almost 12 yearsWith this case or not I believe we should provide best practices :)
-
bfavaretto almost 12 years@user1561559 There was a mistake I just fixed: the line as you posted wouldn't result in assigning
undefined
tolol
, it would cause a js error. -
bfavaretto almost 12 years@MaunoV. You're right, I just added a paragraph about that at the end.
-
nalply almost 12 yearsThe second problem with the first solution is that it reads the input's value not at the exact time the button has been clicked. You solved this quirk with jQuery's val() method in the second solution.
-
viridis over 7 yearsJust a comment, but... why answer using jquery when asking a purely jscript question? jquery is great, but surely not absolutely needed by every single webpage. Maybe the user is to write javascript 100% "pure". Just take a look: youmightnotneedjquery.com