简体   繁体   中英

How to create a modal only if the required fields are filled out before submitting form

I am trying to make a modal appear thanking the user for submitting the form but only if they completely filled out all the required inputs. I like the built in required feature in HTML but currently both pop ups happen when the submit button is pressed. I know an if else statement is required but cannot figure out how to show that the required field is satisfied in JS before popping up the modal.

      <!--   THIS IS THE CONTACT FORM SECTION   -->

<section class="contact-form">
  <h1 class="uptop">CONTACT ME</h1>
  <form method="get">
    <input type="text" class = "name required" id="name" placeholder="NAME" required>
    <input type="email" class="email required" id="email" placeholder="EMAIL" required>
    <textarea id="message" class="message required" rows="5" cols="300" placeholder="MESSAGE"></textarea>
    <input type="submit" class="submit" id="submit" value="Tell Me Something Good" >
  </form>
</section>


<!-- The Modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
  <span class="close">&times;</span>
  <p class ="modal-message">THANKS FOR THAT!</p>
  </div>
</div

JavaScript:

var modal = document.getElementById('myModal');
var btnSubmit = document.getElementById("submit");
var spanClose = document.getElementsByClassName("close")[0];
var requiredFields = document.getElementsByClassName("required").required;


btnSubmit.onclick = function() {
modal.style.display = "block";

}


spanClose.onclick = function() {
modal.style.display = "none";
}

window.onclick = function(event) {
   if (event.target == modal) {
    modal.style.display = "none";
  }
}

I think this could help The innerHTML will do the job

 function check(){ var name = document.getElementById('name').value; if(name!=''){ setStatus("Success"); }else{ setStatus("Error"); } } function setStatus(message){ var inputStatus = document.getElementById('msg'); inputStatus.innerHTML = message; } 
  <input id='name' name='name' /><span id="msg"></span> <button type="submit" onClick="check()">Send</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM