How to access HTML text box from javascript?

How to access HTML text field using javascript function?

+7
javascript html textbox
source share
5 answers

Set the ID property in the text box and use the document.getElementById () function ... Example below:

<html> <head> <script type="text/javascript"> function doSomethingWithTextBox() { var textBox = document.getElementById('TEXTBOX_ID'); // do something with it ... } </script> </head> <body> <input type="text" id="TEXTBOX_ID"> </body> </html> 
+9
source share

Very simple, try the following:

 <!doctype html> <html> <head> … </head> <body> <form> <input id="textbox" type="text" /> </form> <script> var textboxValue = document.getElementById("textbox").value; </script> </body> 

The variable textboxValue will be equal to what you typed in the text box.

Remember that you must put your script if it is written as simple as this after the text field ( input ) appears in your HTML, otherwise when the page first loads, you will get an error because the script is looking for the input field that has not yet been created by the browser.

Hope this helps!

+6
source share

Give your text field an id attribute, and then select it with document.getElementById('<textbox id>') .

+5
source share

First you need to get a DOM (Document Object Model) link to the text box:

 <input type="text" id="mytextbox" value="Hello World!" /> 

Pay attention to the id attribute, the text field now has the identifier mytextbox .

The next step is to get the link in JavaScript:

 var textbox = document.getElementById('mytextbox'); // assign the DOM element reference to the variable "textbox" 

This will retrieve the HTML element using the id attribute. Please note that these identifiers must be unique, therefore you cannot have two text fields with the same identifier.

Now the last step is to get the value of the text field:

 alert(textbox.value); // alert the contents of the textbox to the user 

The value property contains the contents of the text field and what is it!

For more information, you can check out some things in MDC:
GetElementByID Help
Input Element Link
DOM Overview

+5
source share

document.getElementById ('textboxid'). Value or document.formname.textboxname.value

+4
source share

All Articles