首页 > 解决方案 > 不满足条件时显示模态

问题描述

这就是我想要做的:用户必须填写一个表格,如果项目的数量是奇数,一个模式应该弹出一条消息,如果数量是偶数,那么应该提交表单并且不应该弹出模式。我正在尝试使用 AJAX 在 JavaScript 中执行此操作,但没有成功。我是 JavaScript 新手。欢迎任何帮助和想法。这是我到目前为止的代码。

  //this is the submit button, 
  //which if is pressed and the number is odd should trigger the modal
  <input id="myButton" type="submit" class="button_submit" value="Submit">

  <input type="submit" id='myButton' class="button_continue" value="Submit anyway !">
  <a id='button_back' class="button_back">Take me back !</a>
  //these 2 buttons are on the modal, they work

<script>
        var xhr = new XMLHttpRequest();
        var modal = document.getElementById('modal');
        var button = document.getElementById('myButton')
        var page = document.getElementById('content')
        var back = document.getElementById('button_back')
        var message = document.getElementById('warning_msg')
        var item = parseInt(qty_item) (this is the input)


        xhr.onload = function() {
          if (item % 2 != 0) {
            button.onclick = function() {
              modal.style.display = 'flex';
               message.innerHTML='You cannot have an odd number.';
               console.log('Log in 1');
            }
        }
      } else {
        button.onclick = function() {
          modal.style.display = 'none';
           console.log('Log in 2');
      }
    }
    xhr.open("GET", "/new");
    xhr.responseType = "text";
    console.log('About to send')
    xhr.send();
    console.log("This has worked")

标签: javascriptajaxmodal-dialog

解决方案


您应该将奇数/偶数条件移动到按钮单击事件中,如下所示:

xhr.onload = function() {
  button.onclick = function() {
    if (item % 2 !== 0) {
      modal.style.display = 'flex';
      message.innerHTML = 'You cannot have an odd number.';
      console.log('Log in 1');
    } 
    else {
      modal.style.display = 'none';
      console.log('Log in 2');
    }
  }
}

此外,更改id第二个按钮的属性,因为id必须是唯一的


推荐阅读