html оповещение продолжает перенаправлять мою страницу на index.html , Я хочу, чтобы оно просто показывало предупреждение

#javascript #html

#javascript #HTML

Вопрос:

Я пытаюсь сделать так, чтобы моя кнопка отклонения просто выводила предупреждение, прямо сейчас она показывает предупреждение, а затем перенаправляет мою страницу на index.php .

Оно index.php включено в мою форму action="index.php" .

Примечание: Это файл .php.

Извините, если это тривиальный вопрос, я новичок и все еще учусь.

 <!DOCTYPE html>
<html>
   <head>
      <!-- Meta Data -->
      <link rel="stylesheet" type="text/css" href="css/custom.css">
      <link rel="stylesheet" type="text/css" href="css/Privacy.css">
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="description" content="Privacy page">
      <meta name="author" content="groupdev17">
      <!-- Title Data -->
      <title>Privacy Policy</title>
   </head>
   <body>
      <!-- PHP including connection,header, and nav bar -->
      <?php
         include('connection.php');
         include("header.html");
         include("navBar.php");
         ?>
      <!-- class made for contents of privacy statement -->
      <div class="privacyDisplay">
         <p>
         <div class="main-content">
            <h2 id="h2TITLE">PRIVACY STATEMENT</h2>
            <br></br>
            Your privacy is important to us. This privacy statement explains the personal data that we collect and store, how we processes it, and for what purposes. In order for you to add products to a cart and to purchase products from us, we collect and store the following personal information on you:
            <br></br>
            <b>1) Name:</b><br>
            <b>2) Email:</b><br>
            <b>3) Home address:</b><br></br>
            When you complete your purchase by checking out we then collect, but do not store, the following additional information:
            Credit card information
            At no time do we give access to your personal information to third parties.
            In order to continue to use our web site, you must select Accept to indicate that you understand and accept how your personal information is being collected and stored. If you select Decline, then your account will be deactivated and your personal information will no longer be available to anyone. You may still reactivate your account at any time by accepting these terms at a later time. 
            </p>
            <!-- buttons to accept or decline privacy -->
            <form action="index.php" method="get">
            <input name = "answer" type="submit" value="Accept" onclick="acceptFunction()" id="privacyAccept">
            <input name = "answer" type="submit" value="Decline" onclick="declineFunction()" id="privacyDecline">
</form>
         </div>
      </div>
      <!-- copywrite -->
      <div class="container">
         <footer>Victoria Mobile © 2019</footer>
      </div>
      <!-- including footer -->
      <?php
         include("footer.html")
         ?>
      <!-- javascript methods for accept and decline -->
      <script>
         function acceptFunction(){
         
               }
         
         function declineFunction(){
          alert("You must accept the policy agreement to continue");
		return false;

         }
      </script>
   </body>
</html>  

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

1. Хороший вопрос, я думаю, что это тот, который возникает у большинства разработчиков в какой-то момент их карьеры.

Ответ №1:

Ваша кнопка отправляет форму, поэтому вам нужно остановить это, вернув false обработчику нажатия кнопки или изменив тип кнопки с submit на button.

 function declineFunction() {
  alert("You must accept the policy agreement to continue");
  return false;
}  
 <form action="index.php" method="get">
  <input name="answer" type="submit" value="Decline" onclick="return declineFunction()" id="privacyDecline">
</form>  

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

1. Я думаю, вы имеете в виду <input name="answer" type="button" в своем фрагменте.

2. @glhr Нет, на самом деле я этого не делаю, но вы видите в моем ответе, что я предлагаю это в качестве альтернативы.

3. мой плохой. Я думал, что HTML-часть фрагмента предназначена для иллюстрации второго варианта.

Ответ №2:

Просто удалите type="submit" с Decline кнопки. Используйте type="button" вместо:

 <input name="answer" type="button" value="Decline" onclick="declineFunction()" id="privacyDecline">
  

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

1. Готово, вы получили ответ, такой простой и непринужденный. Спасибо G

2. @Karanvir1 meta.stackexchange.com/questions/5234 / …

Ответ №3:

Если вы не хотите отправлять свою форму, используйте кнопку вместо ввода с типом отправки. Таким образом, кнопка будет выполнять действие, которое вы с ней связываете, а не отправлять форму.

 <button type="button" value="Decline" onclick="declineFunction()" id="privacyDecline">
  

Ответ №4:

вы можете использовать preventDefault

 function declineFunction(e) {
  e.preventDefault();
  alert("You must accept the policy agreement to continue");
}  
 <form action="index.php" method="get">
  <input onclick="declineFunction(event)" name="answer" type="submit" value="Decline"  id="privacyDecline">
</form>