HTML Required属性是一个布尔属性, 它指定在提交表单之前必须填写输入元素。该属性与以下元素一起使用:
- <input>
- <select>
- <textarea>
<input>
我们可以通过<input>元素轻松使用required属性, 如以下语法所示:
<input required>
例
<html>
<head>
<title>
Example of required attribute with input element
</title>
<style>
div
{
padding: 10px 0;
}
</style>
<head>
<body>
<form>
<div>
<label>Name</label>
<input type="text" placeholder="Enter Name" name="name" required>
</div>
<div>
<label> E-mail </label>
<input type="email" placeholder="Enter email ID" name="email" required>
</div>
<div>
<label> Mobile No. </label>
<input type="text" placeholder="Enter Your Mobile No." name="mobileno" required>
</div>
<div>
<label>Password</label>
<input type="password" placeholder="Enter Password" name="psw" required>
<br>
</div>
<button type="submit" VALUE="SUBMIT"> SUBMIT </button>
</form>
</body>
</html>
立即测试
输出:
<select>
我们可以使用<select>元素轻松使用required属性, 如以下语法所示:
<select required>
例
<html>
<head>
<title> Example of required attribute with select option </title>
<style>
div
{
padding: 10px 0;
}
</style>
<head>
<body>
<form>
<label>
Course :
</label>
<select required>
<option value="">None</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<button type="submit" VALUE="SUBMIT"> SUBMIT </button>
</form>
</body>
</html>
立即测试
输出:
<textarea>
我们还可以轻松地在<textarea>元素中使用required属性, 如以下语法所示:
<textarea required>
例
<html>
<head>
<title> Example of required attribute with textarea </title>
<style>
div
{
padding: 10px 0;
}
</style>
<head>
<body>
<form>
Any Comment :
<br>
<textarea cols="80" rows="5" placeholder="Enter a comment" value="address" required>
</textarea>
<button type="submit" VALUE="SUBMIT"> SUBMIT </button>
</form>
</body>
</html>
立即测试
输出:
浏览器支持
Element | Chrome | IE | Firefox | Opera | Safari |
<required> | Yes | Yes | Yes | Yes | Yes |