简体   繁体   English

输入字段表单验证 - 复选框

[英]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.我只是在学习输入字段和验证,无法解决问题,以便在检查输入字段时发送 email。 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.在按钮单击事件上调用 validateContact function。

 $(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 并验证表单-

 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. 此处检查样式复选框的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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