I am making a registration form where I gave a checkbox for the terms and conditions. I want to check if the checkbox is checked or not. If it is not checked I want to display a message in the paragraph tag I gave below it
I’ve given this code inside a function made with JQuery which is called when I click a button in the form.
I’ve tried a lot of things from the internet from stackoverflow, gfg, youtube but nothing is working. It’s not even entering the if condition.
The commented function in the end is working though but I want it to work when the button is clicked
function reset() {
document.querySelector(".forms").reset();
}
// $(".fn, .un, .em, .pas, .con").hide();
$(".reg").click(function() {
var fname = $("#fname").val();
if (fname === "") {
$("#fname").css("border", "2px solid red");
$(".fn").html("Fullname is required");
}
var uname = $("#uname").val();
if (uname === "") {
$("#uname").css("border", "2px solid red");
$(".un").html("Username is required");
}
var email = $("#em").val();
if (email === "") {
$("#em").css("border", "2px solid red");
$(".em").html("Email is required");
}
var pass = $("#pass").val();
if (pass.length < 8) {
$("#pass").css("border", "2px solid red");
$(".pas").html("Password must be atleast 8 characters long");
}
var check = $("#check").val();
if (check.equals(pass)) {
$("#check").css("border", "2px solid red");
$(".con").html("Passwords don't match");
}
var tac = $("#tcs").prop("checked");
if (!tac) {
$(".tac").text("You should agree to the terms and conditions");
}
});
$("input").focus(function() {
$(":text, :password").css("border", "0.2px solid grey");
$(":text, :password").css("border-bottom", "3px solid black");
$("#em").css("border", "0.2px solid grey");
$("#em").css("border-bottom", "3px solid black");
$("p").empty();
});
// document.getElementsByClassName("tc").checked;
// function isChecked(){
// if(!document.getElementById("tcs").checked){
// // console.log("Hi");
// $(".tac").html("You must agree to the terms and conditions to continue");
// }
// else{
// // console.log("Bruh");
// $(".tac").empty();
// }
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<input type="checkbox" id="tcs">
<label for="tcs">I have read and agree to the Terms and Conditions</label>
<p class="tac"></p>
3
Answers
The issue is with how you’re trying to check the status of the checkbox using
$("#tcs").checked
.You should check the status of the checkbox input on the change event so it will be called every time the user makes any changes to that checkbox.
Here, is the example code that might meet your requirements.
You can call on the submit button as well to ensure the final state of the checkbox before proceeding further.
Add this click event after you use it