使用 JavaScript 检查元素是否是必需的
Check if an Element is Required using JavaScript
使用该required
属性检查是否需要某个元素,例如
if (element.required) {}
.
该required
属性true
在需要该元素时返回,否则
false
返回。
以下是本文示例的 HTML。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input required type="text" id="first_name" name="first_name" /> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const element = document.getElementById('first_name'); console.log(element.required); // 👉️ true if (element.required) { console.log('✅ element is required'); } else { console.log('⛔️ element is not required'); } // ✅ Set the required attribute // element.setAttribute('required', '') // ✅ Remove the required attribute // element.removeAttribute('required');
true
如果元素是必需的,则元素的 required 属性返回,false
否则返回。
当在元素上设置了
required
属性时,用户必须在提交表单之前为输入指定一个值。
required
property to check if an element is required.Some examples online use the getAttribute()
method on the element, however
boolean attributes like required
might not have a value.
const element = document.getElementById('first_name'); // 👇️ returns an empty string console.log(element.getAttribute('required')); // ❌ DON'T DO THIS if (element.getAttribute('required')) { console.log('✅ element is required'); } else { console.log('⛔️ element is not required'); }
The getAttribute
method returns the value of the provided attribute on the
element.
However, it’s a best practice to set boolean attributes, such as required
,
without a value.
true
.If a boolean attribute is not present, the value of the attribute is considered
to be false
.
Therefore the required
attribute could be set without a value on the element
and the getAttribute
method would return a false negative.
If you need to remove the required
attribute from an element, use the
removeAttribute()
method.
const element = document.getElementById('first_name'); element.removeAttribute('required');
The removeAttribute
method removes the provided attribute from the element.
If you need to set the required
attribute on an element, use the
setAttribute()
method.
const element = document.getElementById('first_name'); element.setAttribute('required', '');
The method takes the following 2 parameters:
name
– the name of the attribute to be set.value
– the value to assign to the attribute.
We provided an empty string as the value for the required
attribute because
it’s a best practice to set boolean attributes without a value.