Bootstrap contact_me.php验证复选框是否已选中?

时间:2018-06-21 13:22:44

标签: javascript validation checkbox bootstrap-4

我正在尝试在我的简单联系表中添加一个复选框。我希望对此进行验证,以便在发送表单之前先进行检查。我非常感谢您的帮助。

FORM:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.7/jqBootstrapValidation.min.js"></script>

    <form id="contactForm" name="sentMessage" novalidate="">
    <div class="control-group form-group">
    <div class="controls"><label>Navn:</label> <input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn." />
    <p class="help-block"> </p>
    </div>
    </div>
    <div class="control-group form-group">
    <div class="controls"><label>Telefonnummer:</label> <input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer." />
    <div class="help-block"> </div>
    </div>
    </div>
    <div class="control-group form-group">
    <div class="controls"><label>E-post:</label> <input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse." />
    <div class="help-block"> </div>
    </div>
    </div>
    <div class="control-group form-group">
    <div class="controls"><label>Melding:</label> <textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
    <div class="help-block"> </div>
    </div>
    </div>


<div class="control-group form-group">
<div class="controls">
      <input class="form-check-input" type="checkbox" value="1" id="personvern" required="" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette" />
      <label class="form-check-label" for="personvern">
        Agree to terms and conditions
      </label>
<div class="help-block"> </div>
    </div>
  </div>



    <div id="success"> </div>
    <!-- For success/fail messages --> <button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></form>

contact_me.js:

$(function() {

  $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    },
    submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit behaviour
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'Kontaktskjema',
    formId: 'contactForm'
  });
      // get values from FORM
      var name = $("input#name").val();
      var email = $("input#email").val();
      var phone = $("input#phone").val();
      var personvern = $("checkbox#personvern").val();
      var message = $("textarea#message").val();
      var firstName = name; // For Success/Failure Message
      // Check for white space in name for Success/Fail message
      if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
      }
      $this = $("#sendMessageButton");
      $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
      $.ajax({
        url: "/mail/contact_me.php",
        type: "POST",
        data: {
          name: name,
          phone: phone,
          email: email,
          personvern: personvern,
          message: message
        },
        cache: false,
        success: function() {
          // Success message
          $('#success').html("<div class='alert alert-success'>");
          $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-success')
            .append("<strong>Takk, meldingen er sendt. </strong>");
          $('#success > .alert-success')
            .append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        error: function() {
          // Fail message
          $('#success').html("<div class='alert alert-danger'>");
          $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-danger').append($("<strong>").text("Beklager " + firstName + ", noe gikk feil med sendingen. Prøv igjen senere!"));
          $('#success > .alert-danger').append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 1000);
        }
      });
    },
    filter: function() {
      return $(this).is(":visible");
    },
  });

  $("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
  $('#success').html('');
});

contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   empty($_POST['personvern'])     ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'email@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Kontaktskjema domain.com:  $name";
$email_body = "Du har mottatt en melding fra kontaktskjemaet paa nettsiden domain.com.\n\n"."Her er meldingen:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
$headers = "From: noreply@domain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";   
mail($to,$email_subject,$email_body,$headers);
return true;         
?>

该表单现在可以正常工作,但是无论我尝试验证什么,如果选中了复选框,它将停止工作。我已经搜索并尝试了所有可以找到的解决方案。

1 个答案:

答案 0 :(得分:0)

我忘了在问题中加入我正在使用jqBootstrapValidation的问题,所以现在我在问题中加入了脚本。我也找到了一个适用的解决方案,其中包含以下复选框代码。 :-)

<div class="control-group">
                            <div class="controls">
                                <label class="checkbox">
                                    <input type="checkbox" id="terms-and-conditions" name="terms-and-conditions" required="" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette" aria-invalid="false">
                                    Ved avkryssning samtykker du i vår <!-- START: Modals --><a href="/personvernerklaering?ml=1" class="modal_link" data-modal-class-name="no_title">personvernerklæring</a><!-- END: Modals -->.
                                </label>
                                <p class="help-block"></p>
                            </div>
                        </div>