event.preventDefault() method in JavaScript
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.
Prevent form submission using preventDefault().
<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.
Prevent 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.
save
listen
AI Answer
event.preventDefault() method in JavaScript
0
The preventDefault() method is used to prevent the browser from executing the default act…
asked
Apu
0 answers
2915
The preventDefault() method is used to prevent the browser from executing the default act…
Answer Link
answered
Apu