Как отображать модальности на странице в зависимости от того, какая кнопка нажата

#javascript #php #html

#javascript #php #HTML

Вопрос:

Извиняюсь за небольшую длину кода. Я пытаюсь открыть модальности на странице, но ничего не происходит, и у меня заканчиваются идеи.

В принципе, если пользователь выбирает кнопку «Курс доступа», модальный с div id01 должен отображаться вместе с его формой. Если нажать кнопку «Сбросить код доступа», будет отображаться только модальный, связанный с id02 .

Я не уверен, что я здесь делаю не так. Я знаю, что в закомментированном коде, если я раскомментирую это и удалю modalFuntion() , то произойдет то, что если я нажму кнопку «Сбросить код доступа», ничего не произойдет, если я нажму кнопку «Доступ к курсу», появятся оба модала.

Код:

      <body>
        
            <div style="text-align: center; margin-top: 2em;">

                <img src="static/images/logo.png">

        <h2>INTRODUCTION TO SOFTWARE TESTING ONLINE COURSE</h2>
        
        <!--<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Access Course</button>-->
        <!--<br/><br/>-->
        <!--<button class="buttonLink" onclick="document.getElementById('id02').style.display='block'" style="width:auto;">Forget Access Code</button>-->
        
        <button onclick="modalFunction()" style="width:auto;">Access Course</button>
        <br/><br/>
        <button class="buttonLink" onclick="modalFunction()" style="width:auto;">Forget Access Code</button>
        
            </div>

        <div id="id01" class="modal">
          
          <form class="modal-content animate" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="imgcontainer">
              <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">amp;times;</span>
            </div>
        
            <div class="container">
              <label for="username"><b>Email</b></label>
              <input type="text" placeholder="Enter Email" name="username" required>
              <span class="help-block"><?php echo $username_err; ?></span>
                <br/><br/>
              <label for="password"><b>Access Code</b></label>
              <input type="text" placeholder="Enter Access Code" name="password" required>
              
              <span class="help-block"><?php echo $password_err; ?></span>
                
              <button type="submit" value="Login" name="Login">Enter</button>
          </form>
        </div>
        
        
        
        <div id="id02" class="modal">
          
          <form class="modal-content animate" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="imgcontainer">
              <span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">amp;times;</span>
            </div>
        
            <div class="container">
                  
              <label for="reset-email"><b>Enter your email to reset your Access Code</b></label>
              <input type="text" placeholder="Enter Email" name="reset username" required>
              <span class="help-block"><?php echo $reset_username_err; ?></span>
                
              <button type="submit" value="Reset" name="Reset">Reset</button>
          </form>
        </div>
        
        
        <script>
        // Get the modal
        var modal = document.getElementById('id01');
        var modal2 = document.getElementById('id02');
        
        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }else if (event.target == modal2){
                modal2.style.display = "none";
            }
        }
        
        function modalFunction(){
            
        document.getElementsByName("Login").onclick = function() {
            modal.style.display = "block";
            modal2.style.display = "none";
        }
        
        document.getElementsByName("Reset").onclick = function() {
            modal2.style.display = "block";
            modal.style.display = "none";
        }
        }
        
        </script>
        <?php if($_SERVER["REQUEST_METHOD"] == "POST"){
            switch ($_POST["submit"]) {
            case "Login":
                echo "<script>document.getElementById('id01').style.display='block';</script>";
              break;
          case "Reset":
              echo "<script>document.getElementById('id02').style.display='block';</script>";
              break;
          default:
              break;
            }
            
  }
    ?>
  

Ответ №1:

Закрывающие теги обоих ваших модальных элементов инвертируются.

Они оба сначала закрывают form , а затем div , но должно быть наоборот, а также </div> отсутствует (я улучшил идентификацию, чтобы лучше визуализировать проблему):

 <div id="id01" class="modal">
    <form class="modal-content animate" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="imgcontainer">
            <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">amp;times;</span>
        </div>
    
        <div class="container">
            <label for="username"><b>Email</b></label>
            <input type="text" placeholder="Enter Email" name="username" required>
            <span class="help-block"><?php echo $username_err; ?></span>
            <br/><br/>
            <label for="password"><b>Access Code</b></label>
            <input type="text" placeholder="Enter Access Code" name="password" required>
            <span class="help-block"><?php echo $password_err; ?></span>    
            <button type="submit" value="Login" name="Login">Enter</button>
        </div>
    </form>
</div>
  

И то же самое касается id="id02" модального.

Комментарии:

1. Вы тот, кого мы называем сэр легенда. Спасибо