The HTML value attribute specifies the initial or default value for various elements.
Definition and Usage
➔ The following elements use the value attribute:
- For <input>: The value attribute specifies the initial value of the input field.
- For type="text", "password", "hidden": The value attribute specifies the initial text or value.
- For type="submit", "reset", "button", "image": The value attribute specifies the text displayed on the button.
- For type="checkbox", "radio": The value attribute specifies the value associated with input of the element.
- For <button>: The value attribute specifies the initial value of the button element.
- For <option>: The value attribute specifies the value of the element, if the attribute is missing then the content will be treated as the value.
- For <li>: The value attribute specifies the ordinal value of an item in an ordered list, and subsequent list items will increment from the new value.
- For <meter>: The value attribute specifies the current value.
- For <progress>: The value attribute specifies how much task has been completed.
- For <param>: The value attribute specifies the parameter value of an embedded object.
- For <data>: The value attribute specifies the machine-readable value of an element's human-readable content.
Syntax
<!-- Input field value -->
Name:<input type="text" id="name" name="name" value="M. John"><br><br>
<!-- Submit button value -->
<input type="submit" value="Submit Data"><br><br>
<!-- options value -->
<select name="fruits">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<!-- Ordered list item value -->
<ol>
<li value="10">Berry</li>
<li>Cherry</li>
</ol>
<!-- data value -->
<ul>
<li><data value="52241">Apple</data></li>
<li><data value="52242">Berry</data></li>
<li><data value="52243">Cherry</data></li>
</ul>
//In JavaScript
//const element = document.getElementById('name');
//element.value= 'John';
//element.setAttribute('value', 'John');
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML value attribute example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML value attribute example</h3>
<p>The value attribute specifies the initial or default value for an element.</p>
<div>
<!-- Input field value -->
Name:<input type="text" id="name" name="name" value="M. John"><br><br>
<!-- Submit button value -->
<input type="submit" value="Submit Data" onclick="m1()"><br><br>
<!-- options value -->
<select name="fruits">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<!-- Ordered list item value -->
<ol>
<li value="10">Berry</li>
<li>Cherry</li>
</ol>
<!-- data value -->
<ul>
<li><data value="52241">Apple</data></li>
<li><data value="52242">Berry</data></li>
<li><data value="52243">Cherry</data></li>
</ul>
</div>
<script>
function m1() {
const element = document.getElementById('name');
let x = element.value;
alert(x);
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.