我有一个带有姓名、电子邮件和文本输入以及提交按钮的表单。单击提交检查字段以确保其中有文本。如果字段中有文本,单击提交应提交表单信息并将按钮的文本更改为“已发送!”
无论出于何种原因,我都不知道如何更改按钮文本。
const nameField = document.querySelector("#name-field").value;
const emailField = document.querySelector("#email-field").value;
const textField = document.querySelector("#message-field").value;
const form = document.querySelector(".form");
const formButton = document.querySelector(".form-button");
form.addEventListener("click", validateField);
function validateField(event) {
event.preventDefault();
if (nameField === "") {
$('#name-field').attr('placeholder', 'Please enter your name.');
$('#name-field').addClass('needText');
}
if (emailField === "") {
$('#email-field').attr('placeholder', 'Please enter your email.');
$('#email-field').addClass('needText');
}
if (textField === "") {
$('#message-field').attr('placeholder', 'Please enter your message.');
$('#message-field').addClass('needText');
} else {
formButton.innerText = "Sent!";
}
}
您需要从逻辑中提取验证逻辑以向用户显示反馈。它们将被单独处理。
您可以通过使用 OR 运算符重新检查所有值来做到这一点,或者只使用一个变量来跟踪它。
const nameField = document.querySelector("#name-field").value;
const emailField = document.querySelector("#email-field").value;
const textField = document.querySelector("#message-field").value;
const form = document.querySelector(".form");
const formButton = document.querySelector(".form-button");
let emptyFieldFound = false;
form.addEventListener("click", validateField);
function validateField(event) {
event.preventDefault();
if (nameField === "") {
emptyFieldFound = true;
$('#name-field').attr('placeholder', 'Please enter your name.');
$('#name-field').addClass('needText');
}
if (emailField === "") {
emptyFieldFound = true;
$('#email-field').attr('placeholder', 'Please enter your email.');
$('#email-field').addClass('needText');
}
if (textField === "") {
emptyFieldFound = true;
$('#message-field').attr('placeholder', 'Please enter your message.');
$('#message-field').addClass('needText');
}
if (!emptyFieldFound) {
formButton.innerText = "Sent!";
}
}
就是说,我鼓励您研究现代 HTML5 表单验证。您可以使用
required
输入属性和表单有效性属性自动执行您在这里所做的一些事情。
const nameField = document.querySelector("#name-field").value;
您的选择仅选择此 DOM 元素的值,您可以尝试这种方式
$(".form").submit(validateField());
function validateField(event) {
event.preventDefault();
if ($("#name-field").val() === "") {
$("#name-field").attr("placeholder", "Please enter your name.");
$("#name-field").addClass("needText");
}
if ($("#email-field").val() === "") {
$("#email-field").attr("placeholder", "Please enter your email.");
$("#email-field").addClass("needText");
}
if ($("#message-field").val() === "") {
$("#message-field").attr("placeholder", "Please enter your message.");
$("#message-field").addClass("needText");
} else {
$("#message-field").html("Sent!");
}
}