最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - console.log not executed in on('submit') if event.preventDefault() is not done - Stack Overflow

programmeradmin1浏览0评论

This is really strange:

$('form').on('submit', function(event) {
   console.log('submit > this=%o', this);
});

Will not show any console message when the form is submitted, but this:

 $('form').on('submit', function(event) {
   console.log('submit > this=%o', this);
   event.preventDefault();
 });

Will show it. Why is that? The code must get executed in any case, so that the preventDefault has any effect!

I have only tested in Chrome, and I would say this is a Chrome bug. Or am I missing sth here?

This is really strange:

$('form').on('submit', function(event) {
   console.log('submit > this=%o', this);
});

Will not show any console message when the form is submitted, but this:

 $('form').on('submit', function(event) {
   console.log('submit > this=%o', this);
   event.preventDefault();
 });

Will show it. Why is that? The code must get executed in any case, so that the preventDefault has any effect!

I have only tested in Chrome, and I would say this is a Chrome bug. Or am I missing sth here?

Share Improve this question asked Nov 9, 2015 at 1:18 blueFastblueFast 44.7k66 gold badges214 silver badges374 bronze badges 3
  • This might be a security feature, interesting. – Olavi Sau Commented Nov 9, 2015 at 1:21
  • 1 activate the 'permanent'-option(preserve log) of the console. When you submit the form you leave the document and the console will be cleared by default – Dr.Molle Commented Nov 9, 2015 at 1:29
  • @Dr.Molle: oooops! It was driving me crazy, so much that I oversaw this little detail! – blueFast Commented Nov 9, 2015 at 1:39
Add a ment  | 

2 Answers 2

Reset to default 7

The code actually works, the problem is that the console is being cleared immediately because the page was reloaded due to the form submission.

The code event.preventDefault(); has prevented the form from being submitted. This is why the console is not cleared and you are able to see the text being logged.

Works as expected here :)

$('form').on('submit',function(e){
console.log('hell',this)
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://www.google." method="POST">
  Field:<br>
  <input type="text" name="firstname">
  <input type="submit" name="submit">
</form>

发布评论

评论列表(0)

  1. 暂无评论