Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu June 03, 2023 . #Form . #HowTo

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 :-

  1. Use preventDefault() method.
  2. Prevent a html form from submission.
  3. Prevent a checkbox from being checked.
save
listen
AI Answer
Write Your Answer
loading
back
View All