JavaScript 表单验证 - textarea 字段在没有输入文本时显示警告

JavaScript form Validation - textarea field to display an alert if no text has been entered

我似乎无法在该函数中定位 textarea 字段。

我基本上对前三个输入字段使用 HTML“必需”验证,但对于文本区域,我只是想在用户提交表单时如果文本区域字段为空时显示警告.

或者,如果用户试图在未填写该区域的情况下提交表单,我可能希望在文本区域字段中显示文本,说明“请输入更多信息”。

      <form action="" class="contactForm" method="POST" id="contactForm">
                        <label for="name">Name:</label>
                        <input type="text" id="name" name="name" required><br>
                        <label for="number">Number:</label>
                        <input type="number" id="number" name="number" required><br>
                        <label for="email">Email:</label>
                        <input type="email" id="email" name="email" required><br>
                        <textarea id= "textArea" rows ="3" cols ="23" name="finalMessage " form="contactForm" placeholder="Enter your fitness goals..."></textarea><br>
                        <button id="buttonID">Submit</button>
                    </form>

JavaScript


function formValidation(e) {
    e.preventDefault();
    const form = document.getElementById("contactForm");
    const textArea = document.getElementById("textArea").value;

    if(textArea.value === ""){
        alert("please enter more information");
    }

    document.getElementById("buttonID").addEventListener("click", function () {
        form.submit();
    });

} formValidation();

您可以试试下面的方法。在表单上添加一个 onSubmit 事件并删除所有其他事件。在 formValidation() 函数中添加一个 if 条件,如下所示。

if (!textArea.value) {
    alert("please enter more information");
  }

现在,当所有其他输入字段都已填写且只有文本区域为空时,它会显示警告消息。

注意:仅当姓名、号码和电子邮件字段中有一些时,才会显示警报消息

工作代码:

function formValidation() {
  const form = document.getElementById("contactForm");
  const textArea = document.getElementById("textArea").value;
  if (!textArea.value) {
    alert("please enter more information");
  }
}
<form action="" class="contactForm" method="POST" id="contactForm" onSubmit="formValidation()">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required><br>
  <label for="number">Number:</label>
  <input type="number" id="number" name="number" required><br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required><br>
  <textarea id="textArea" rows="3" cols="23" name="finalMessage " form="contactForm" placeholder="Enter your fitness goals..."></textarea><br>
  <button id="buttonID">Submit</button>
</form>

好的,让我们从onsubmit事件侦听器开始:

<form action="" class="contactForm" method="POST" id="contactForm" onsubmit="formValidation(event)">

然后简化formValidation方法:

function formValidation(event) {
    if (document.getElementById("textArea").value == "") {
        alert("please enter more information");
            event.preventDefault();
    }
}

如果您想知道为什么您的代码不起作用,请查看已经包含文本区域值的 textArea 变量。 然后查看您尝试从字符串中获取参数值的条件。