The preventDefault() method is used to prevent the browser from executing the default action of a selected element. It means that the default action that belongs to a particular event will not occur. For example, whenever someone clicks on a Submit button, this method presents it from submitting the form.
How to prevent default form submission.
By default, a submit event is fired and also refreshed the current page when a form is submitted. Using this preventDefault() method , we can stop the page from refreshing.
<form id="my-form">
<input type="submit" value="Submit">
</form>
<script>
document.querySelector('#my-form').onsubmit = function(e){
e.preventDefault();
}
</script>
Try it Yourself »
How to prevent checkbox from being checked.
Using the preventDefault() method , we can also prevent the input type="checkbox" from being checked.
<input type="checkbox" id="my-checkbox">
<script>
document.querySelector('#my-checkbox').onclick = (myE)=>{
myE.preventDefault();
}
</script>
Try it Yourself »
Conclusion
In this article, you have learned how to :-
- Use preventDefault() method.
- Prevent a html form from submission.
- Prevent a checkbox from being checked.
Comments (0)