Blog

Home  /  Coding   /  How to Check If Checkbox is Checked | AV CODING

How to Check If Checkbox is Checked | AV CODING

Hey guys welcome to AV Coding

Today we will learn how to check if the checkbox was checked or not using JQuery and JavaScript and then send the data to the server.

The complete code is explained in the video below and the source code is provided below.

<!DOCTYPE html>
<html>
<head>
	<title>How to Check If Checkbox is Checked | AV Coding</title>
	<meta charset="UTF-8">
</head>
<body style="text-align: center; margin-top: 20%;">

	<form action="./index.html" id="myForm">

		Accept Terms & Conditions: <input type="checkbox" id="myCheck">

		<br>
		<br>

		<button id="button" type="submit">Submit Button</button>

		<br>
		<br>

		<a href="./index.html" id ="anchor">Submit Anchor Tag</a>

	</form>


	<!-- Jquery CDN JS Link -->
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>


	<!-- Method 1: Preventing Form Submit -->
	<script type="text/javascript">
		 $("#myForm").submit(function(e){
	        e.preventDefault();

	        if($('#myCheck').is(":checked")){
		    	$(this).unbind("submit").submit();
		    }	
	    });
	</script>


	<!-- Method 2: Preventing anchor tag -->
	<script type="text/javascript">
		var tempHref = $("#anchor").attr("href");
		$("#anchor").attr("href", '#');

		$("#myCheck").click(function(){
			if($('#myCheck').is(":checked")){
				$("#anchor").attr("href", tempHref);
			}else{
				$("#anchor").attr("href", '#');
			}
		});
	</script>


	<!-- Method 3: Disable submit button -->
	<script type="text/javascript">
		$('#button').attr("disabled", true);

		$("#myCheck").click(function(){
			if($('#myCheck').is(":checked")){
				$('#button').attr("disabled", false);
			}else{
				$('#button').attr("disabled", true);
			}
		});
	</script>

</body>
</html>

Hope You Liked This Blog. Share, Comment, Subscribe And Press The Bell Icon In The Bottom Right Side For More Code Feeds.