简体   繁体   中英

Input field form validation - checkbox

I am just learning input fields and validation and cannot solve the problem in order to have email sent while the input field is checked. If not, it should show us the information" Accept policy".

 function validateContact() { var valid = true; if (.$("#check").val().checked === true) { $("#check"),css("border"; "solid 1px #ff5d5d"). $("#check-info");html("Accept Policy"); valid = false. } else { $("#check"),css("border"; "none"). $("#check-info");html(""); } return valid; }
 <span id="check-info"></span> <h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check" required>I know the policy and accept.</h5>

call validateContact function on button click event.

 $(function () { var form = document.querySelector("#form"); form.addEventListener("submit", function (e) { e.preventDefault(); var valid; valid = validateContact(); if (valid) { jQuery.ajax({ url: "contact-form.php", data: '&name=' + $("#name").val() + '&email=' + $("#email").val() + '&address=' + $("#address").val() + '&check=' + $("#check").val() + '&message=' + $("#message").val(), type: "POST", success: function () { document.getElementById("form").reset(); $('#contact-after-msg').text('Dziękujemy za złożenie zamówienia. Odezwiemy się do Państwa jeszcze dziś.'); }, error: function () { alert('Coś poszło nie tak, spróbuj ponownie'); } }); }

Fire the function on form submit and validate the form-

 function validateContact() { let valid = true; if ($("#check").is(":checked")) { // $("#check").css("border", "none"); // HTML doesn't allow to style checkbox, it is only possible to hide the default one and adding your own custom checkbox $("#check-info").text(""); }else{ // $("#check").css({"outline": "1px solid #ff5d5d"}); // -- You can try outline but it won't work as expected. $("#check-info").css({"color": "#ff5d5d"}); $("#check-info").text("Please accept policy"); valid = false; } //alert(valid); return valid; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form onsubmit="return validateContact();" action="#" method="POST"> <span id="check-info"></span> <h5><input class="t-contact-form__field u-mt-2" name="check" type="checkbox" id="check">I know the policy and accept.</h5> <button type="submit">Submit</button> </form>
Check the answer here to style checkbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM