在JavaScript中,清空表单(form)中的所有输入值(values)有多种方法。以下是几种常用的方法及其示例代码:
使用表单的 reset()
方法可以将表单中的所有输入字段重置为它们的默认值(通常是空值)。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>重置表单示例</title>
</head>
<body>
<form id="myForm">
<input type="text" name="username" value="默认用户名"><br><br>
<input type="password" name="password"><br><br>
<button type="button" onclick="resetForm()">重置表单</button>
</form>
<script>
function resetForm() {
document.getElementById('myForm').reset();
}
</script>
</body>
</html>
优势:
通过遍历表单中的所有输入元素,并将它们的值设置为空字符串,可以清空所有用户输入的数据。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>清空表单示例</title>
</head>
<body>
<form id="myForm">
<input type="text" name="username"><br><br>
<input type="password" name="password"><br><br>
<button type="button" onclick="clearForm()">清空表单</button>
</form>
<script>
function clearForm() {
const form = document.getElementById('myForm');
const elements = form.elements;
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const type = element.type.toLowerCase();
// 根据不同类型的输入元素进行处理
if (type === 'text' || type === 'password' || type === 'textarea') {
element.value = '';
} else if (type === 'checkbox' || type === 'radio') {
element.checked = false;
} else if (type === 'select-one' || type === 'select-multiple') {
element.selectedIndex = -1;
}
}
}
</script>
</body>
</html>
优势:
FormData
对象FormData
对象可以用于获取和设置表单数据,通过重新赋值可以清空表单。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>使用FormData清空表单</title>
</head>
<body>
<form id="myForm">
<input type="text" name="username"><br><br>
<input type="password" name="password"><br><br>
<button type="button" onclick="clearFormWithFormData()">清空表单</button>
</form>
<script>
function clearFormWithFormData() {
const form = document.getElementById('myForm');
const formData = new FormData(form);
for (let pair of formData.entries()) {
const input = form.querySelector(`[name="${pair[0]}"]`);
if (input) {
if (input.type === 'checkbox' || input.type === 'radio') {
input.checked = false;
} else {
input.value = '';
}
}
}
}
</script>
</body>
</html>
优势:
FormData
对象,便于后续的数据处理和传输。通过以上方法,可以根据具体需求选择最适合的方式来清空JavaScript中的表单值。
领取专属 10元无门槛券
手把手带您无忧上云