JavaScript表单验证代码错误

JavaScript form validation code errors

本文关键字:错误 代码 验证 表单 JavaScript      更新时间:2023-09-26

下面是我的代码:

<!DOCTYPE html>
<head>
  <title>Tests</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf8'>
<script type="text/javascript">
      function closeSign(){
        document.getElementById('window_fler').style.display = 'none';      
        document.getElementById('wrap_fler').style.display = 'none'; 
      }
      function validate_fler(){
          if (document.forms["fler_form"]["signDate"].value.length == 0) { return false };
          if (document.forms["fler_form"]["signTime"].value.length == 0) { return false };
          if (document.forms["fler_form"]["signFIO"].value.length == 0) { return false };
          if (document.forms["fler_form"]["signPhone"].value.length == 0) { return false };
          document.getElementById('window_fler').style.display = 'block';      
          document.getElementById('wrap_fler').style.display = 'block';     
      }
    </script>
<style type="text/css">
  #wrap_fler{
    display: none;
    opacity: 0.8;
    position: fixed;
    background-color: rgba(1, 1, 1, 0.725);
    z-index: 100;
    overflow: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 16px;
  }
  #window_fler{
    height: 400px;
    width: 400px;
    display: none;
    z-index: 200;
    position: fixed;
    margin: 150px auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 30px;
    background: #fff;
  } 
</style>
</head>
<body>

  <form role="form" name="fler_form" action="" data-email-subject="Contact Form" data-show-errors="true">
                                       <div>
                                           <label for="dayTime1">Выберите дату:</label>
                                           <input name="signDate" type="text" placeholder="Пожалуйста, выберите дату" id="dayTime1" required>
                                       </div>
                                       <div>
                                           <label for="hourTime">Выберите время:</label>
                                           <select name="signTime" id="hourTime">
                                         <option>&nbsp;</option>
                                               <option value="10">10:00</option>
                                               <option value="11">11:00</option>
                                               <option value="12">12:00</option>
                                               <option value="13">13:00</option>
                                               <option value="14">14:00</option>
                                               <option value="15">15:00</option>
                                               <option value="16">16:00</option>
                                               <option value="17">17:00</option>
                                               <option value="18">18:00</option>
                                               <option value="17">19:00</option>
                                               <option value="18">20:00</option>
                                           </select>
                                       </div>
                                       <div>
                                           <label for="fio">Ваше имя и фамилия:</label>
                                           <input name="signFIO" type="text" placeholder="Пожалуйста, введите Ваше имя и фамилию" id="fio" required>
                                       </div>
                                       <div>
                                           <label for="phone">Номер телефона:</label>
                                           <input name="signPhone"  type="text" placeholder="Пожалуйста, введите Ваш номер телефона" id="phone" required>
                                       </div>

                                       <div>
                                       <button type="submit" onclick="return validate_fler()">
                                       <span>Записаться</span></button>
                                       </div>
                                   </form>
                                   <div id="wrap_fler" onclick="closeSign()"></div>
                                       <div id="window_fler">
                                        <h3>
                                             Ваша заявка принята. <br/>
                                          В ближайшее время с вами свяжется администратор нашего салона, что бы подтвердить запись.
                                        </h3>
                                         <a href="#" onclick="closeSign()" style="margin: 30px 0 0 0;">ЗАКРЫТЬ</a>
                                      </div>
</body>
</html>

我需要验证表单是否存在所有字段。接下来,我需要向用户显示div window_fler中的消息。用户可以单击按钮来关闭div。在我的情况下,当我在表单中单击按钮时,我看到消息div显示并快速关闭。我的代码有什么问题?

正如Mayank指出的那样,您的表单是在点击按钮时提交的,这会导致您的页面状态发生变化。

<button type="submit" onclick="return validate_fler()">
<span>Записаться</span></button>

尝试将此按钮的类型更改为"button",并在代码的其他地方单独处理提交。

<button type="button" onclick="return validate_fler()">
<span>Записаться</span></button>

你可以尝试像两个单独的按钮:"验证"answers"提交表单"。

在下面的块中,只有当字段无效时才返回false。显示模态或弹出窗口后返回false,因此表单将不会被提交。

function validate_fler() {
  if (document.forms["fler_form"]["signDate"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signTime"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signFIO"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signPhone"].value.length == 0) {
    return false
  };
  document.getElementById('window_fler').style.display = 'block';
  document.getElementById('wrap_fler').style.display = 'block';
  return false;// added this to prevent form submission
}

你没有提到你想如何提交表单后显示一个弹出窗口,所以这只是一个小的修复你的问题。如果你能说出你真正想要达到的目标,我会更新我的帖子

使用AJAX (JQuery)提交表单

function SubmitForm() {
  var datastring = $("[name=fler_form]").serialize();
  alert(datastring)// this is the form data.
  $.ajax({
    type: "POST",
    url: "#the url of server to send data",
    data: datastring,
    dataType: "json",
    success: function(data) {
      //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
      // do what ever you want with the server response
    },
    error: function(errorObj) {
      console.log(errorObj)
    }
  });
}

function closeSign() {
  document.getElementById('window_fler').style.display = 'none';
  document.getElementById('wrap_fler').style.display = 'none';
}
function validate_fler() {
  if (document.forms["fler_form"]["signDate"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signTime"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signFIO"].value.length == 0) {
    return false
  };
  if (document.forms["fler_form"]["signPhone"].value.length == 0) {
    return false
  };
  document.getElementById('window_fler').style.display = 'block';
  document.getElementById('wrap_fler').style.display = 'block';
}
function SubmitForm() {
  var datastring = $("[name=fler_form]").serialize();
  alert(datastring)
  $.ajax({
    type: "POST",
    url: "#the url of server to send data",
    data: datastring,
    dataType: "json",
    success: function(data) {
      //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
      // do what ever you want with the server response
    },
    error: function(errorObj) {
      console.log(errorObj)
    }
  });
}
#wrap_fler {
   display: none;
   opacity: 0.8;
   position: fixed;
   background-color: rgba(1, 1, 1, 0.725);
   z-index: 100;
   overflow: auto;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
   padding: 16px;
 }
 #window_fler {
   height: 400px;
   width: 400px;
   display: none;
   z-index: 200;
   position: fixed;
   margin: 150px auto;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
   padding: 30px;
   background: #fff;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <form role="form" name="fler_form" action="" data-email-subject="Contact Form" data-show-errors="true">
    <div>
      <label for="dayTime1">Выберите дату:</label>
      <input name="signDate" type="text" placeholder="Пожалуйста, выберите дату" id="dayTime1" required>
    </div>
    <div>
      <label for="hourTime">Выберите время:</label>
      <select name="signTime" id="hourTime">
        <option>&nbsp;</option>
        <option value="10">10:00</option>
        <option value="11">11:00</option>
        <option value="12">12:00</option>
        <option value="13">13:00</option>
        <option value="14">14:00</option>
        <option value="15">15:00</option>
        <option value="16">16:00</option>
        <option value="17">17:00</option>
        <option value="18">18:00</option>
        <option value="17">19:00</option>
        <option value="18">20:00</option>
      </select>
    </div>
    <div>
      <label for="fio">Ваше имя и фамилия:</label>
      <input name="signFIO" type="text" placeholder="Пожалуйста, введите Ваше имя и фамилию" id="fio" required>
    </div>
    <div>
      <label for="phone">Номер телефона:</label>
      <input name="signPhone" type="text" placeholder="Пожалуйста, введите Ваш номер телефона" id="phone" required>
    </div>
    <div>
      <button type="button" onclick="return validate_fler()"> <span>Записаться</span>
      </button>
    </div>
  </form>
  <div id="wrap_fler" onclick="closeSign()"></div>
  <div id="window_fler">
    <h3>
                                             Ваша заявка принята. <br/>
                                          В ближайшее время с вами свяжется администратор нашего салона, что бы подтвердить запись.
                                        </h3>
    <a href="#" onclick="closeSign()" style="margin: 30px 0 0 0;">ЗАКРЫТЬ</a>
    <button type="button" onclick="SubmitForm()"> <span>Submit</span>
    </button>
  </div>
</body>

替换<button type="submit" onclick="return validate_fler()"> <span>Записаться</span></button>

<input type="button" onclick="return validate_fler()">
                                   <span>Записаться</span></input>

试试这个。这不会提交你的表单,所以你可以让你的js代码正常工作。对于你所要求的,我已经给出了解决办法。

Try

 if (document.forms["fler_form"]["signDate"].value.length == 0 || 
   document.forms["fler_form"]["signTime"].value.length == 0 || 
   document.forms["fler_form"]["signFIO"].value.length == 0 || 
   document.forms["fler_form"]["signPhone"].value.length == 0) { 
       document.getElementById('window_fler').style.display = 'block';      
       document.getElementById('wrap_fler').style.display = 'block'; 
};

return false在那里没有任何意义,它不会执行后面的语句。如果条件为真,则必须执行display:block;