完成必填字段后如何允许提交表单?

我已经完成了带有即时字段验证的代码,但也希望在字段没有值的情况下防止提交表单。我已经设法阻止提交表单,但是当我返回并提供一个值时,它仍然不允许它提交。知道我在这里做错了什么吗?


这是 HTML:


<form id="contactForm" action="https://formspree.io/xrggbejj" method="POST" onsubmit="return formValidation(contactForm);">


  <div class="row">


  <div class="col">

    <label for="fName">First Name</label>

  </div>


  <div class="col">

    <input type="text" id="fName" name="firstname" onblur="checkFirstName(firstName)" autofocus/>

    <img src="../images/alert-icon.png" class="alert" id="firstNameMsg" alt="alert icon" width="40" height="35"/>

  </div>

  </div> <!-- End of row -->


  <div class="row">


  <div class="col">

    <label for="lName">Last Name</label>

  </div>


  <div class="col">

    <input type="text" id="lName" name="lastname" onblur="checkLastName(lastName)"/>

    <img src="../images/alert-icon.png" class="alert" id="lastNameMsg" alt="alert icon" width="40" height="35"/>

  </div>

  </div> <!-- End of row -->


  <div class="row">


  <div class="col">

    <label for="subject">Questions and/or Comments</label>

  </div>


  <div class="col">

    <textarea id="subject" name="subject" onblur="checkSubject(subject)" style="height:200px"></textarea>

    <img src="../images/alert-icon.png" class="alert" id="subjectMsg" alt="alert icon" width="40" height="35"/>

  </div>

  </div> <!-- End of row -->


  <div class="row">

    <input type="submit" value="SEND" />

  </div> <!-- End of row -->

</form>


慕森卡
浏览 217回答 2
2回答

湖上湖

的firstName,lastName和subject可变指向的输入不是他们的实际值的内侧。您可以将函数修改为&nbsp; &nbsp; function formValidation(contactForm) {&nbsp; &nbsp; &nbsp; if (!firstName.value || !lastName.value || !subject.value) {&nbsp; &nbsp; &nbsp; &nbsp; alert('Please fill out required fields.')&nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault()&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }在这里,我使用!运算符将输入转换True为空时,如果任何输入为空,则将评估第一种情况,否则您的函数将返回 true。

至尊宝的传说

既然你这样做if (firstName && lastName && subject !== true) {&nbsp; ...}我假设你希望这样做&nbsp;if (firstName.value === '') {&nbsp; &nbsp; alertStyle = document.getElementById('fName').style.border = '2px solid rgba(255, 6, 0)';&nbsp; &nbsp; alertImg = document.getElementById('firstNameMsg').style.display = 'inline-block';&nbsp; &nbsp; return false;会做这样的事情firstName = true但它实际上并没有为firstName. 它只是返回真。你可以有一个变量 like isValidand doisValid = true而不是在你的checkLastName() etc..但是,既然你这样做document.getElementById('lastNameMsg').style.display = 'none'你可以做function formValidation(contactForm) {&nbsp; if (document.getElementById('lastNameMsg').style.display !== 'none') {&nbsp; &nbsp; alert('Please fill out required fields.')&nbsp; &nbsp; event.preventDefault()&nbsp; &nbsp; return false;&nbsp; } else if (document.getElementById('lastNameMsg').style.display === 'none') {&nbsp; &nbsp; return true;&nbsp;}}无论如何,有多种方法可以简化,但希望这能让你继续前进:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript