Example
Change the value of a text field:
document.getElementById("myText").value = "Johnny Bravo";
Try it Yourself »
Definition and Usage
The value property sets or returns the value of the value attribute of a text field.
The value property contains the default value OR the value a user types in (or a value set by a script).
Browser Support
The value property is supported in all major browsers.
Syntax
Return the value property:
textObject.value
Set the value property:
textObject.value=text
Property Values
Value | Description |
---|---|
text | Specifies the value of the input text field |
Technical Details
Return Value: | A String, representing the value of the text field |
---|
More Examples
Example
Get the value of a text field:
var x = document.getElementById("myText").value;
The result of x will be:
Mickey
Try it Yourself »
Example
Form validation:
var at = document.getElementById("email").value.indexOf("@");
var age =
document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
alert("The name may have no more than 10 characters");
submitOK =
"false";
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK =
"false";
}
if (at == -1) {
alert("Not a
valid e-mail!");
submitOK = "false";
}
if (submitOK == "false")
{
return false;
}
Try it Yourself »
Example
Dropdown list in a form:
var mylist = document.getElementById("myList");
document.getElementById("favorite").value = mylist.options[mylist.selectedIndex].text;
Try it Yourself »
Example
Another dropdown list:
var no = document.getElementById("no");
var option = no.options[no.selectedIndex].text;
var txt = document.getElementById("result").value;
txt = txt + option;
document.getElementById("result").value = txt;
Try it Yourself »
Example
An example that shows the difference between the defaultValue and value property:
var x = document.getElementById("myText");
var defaultVal =
x.defaultValue;
var currentVal = x.value;
Try it Yourself »
Related Pages
HTML reference: HTML <input> value attribute
< Input Text Object