[javascript] How to get an input text value in JavaScript

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?

This question is related to javascript text input get

The answer is


<script type="text/javascript">
function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}


</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" id="lolz" value=""/>
    <input type="button" value="click" onclick="kk();"/>
</body>

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:

<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:

language = cdata [CI]

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. […]


as your lol is local variable now, its good practice to use var keyword for declaring any variables.

this may work for you :

function kk(){
  var lol = document.getElementById('lolz').value;
  alert(lol);
}

<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value) 
window.alert(subadd)  
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>

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.


How to get an input text value in JavaScript

_x000D_
_x000D_
    var textbox;_x000D_
    function onload() { _x000D_
        //Get value._x000D_
        textbox = document.getElementById('textbox');_x000D_
    }_x000D_
_x000D_
    function showMessage() { _x000D_
        //Show message in alert()_x000D_
        alert("The message is: " + textbox.value);_x000D_
    }
_x000D_
<body onload="onload();">_x000D_
<div>_x000D_
<input type="text" name="enter" class="enter" placeholder="Write something here!" value="It´s a wonderful day!" id="textbox"/>_x000D_
<input type="button" value="Show this message!" onClick="showMessage()" />_x000D_
</div>
_x000D_
_x000D_
_x000D_


Edit:

  1. 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).
  2. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
  3. Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
  4. To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
  5. Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
    function har() {
        var txt_val;
        txt_val = document.getElementById("har").value;
        alert(txt_val);
    }
</script>

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.


All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.


document.getElementById('id').value


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?