0

In my Rails app, I am using this jQuery to prevent a form from being submitted when the user presses 'enter' in an input field:

$('input').on('keydown', function(e) {
  if(e.which == '13') {
    return false;
  }
})

I wrote a test in Capybara to make sure the form was not being submitted (more on that here), and had a hell of a time getting the test to work properly. Eventually I discovered that the jQuery function had to target a keydown event, not keypress. It works wonderfully now.

This makes me a bit uncomfortable, because I know that keypress should work just as well, and I know that it actually does work from trying it manually in the browser. But if I want to have a working test for this behavior, I have to do it with keydown.

This is the command that I'm sending to Webkit in my integration test:

page.driver.browser.execute_script "var e = jQuery.Event('keydown'); e.which = 13; $('#shift_employee').trigger( e );"

It goes without saying that when I change the jQuery function to handle keypress instead of keydown, I also change the Ruby line above to trigger a keypress event instead of a keydown event. But the test fails unless I use keydown.

So what's the deal? Is this a Webkit issue? Should I not worry about it, as long as the test is working and the form is not being submitted?

4

1 回答 1

0

我相信你是在想这个问题。表单被提交是enter因为您在表单中有一个提交按钮。因此,如果您不想要这种行为,您有以下选择:

从表单中删除提交按钮。如果您需要该按钮进行其他操作,您可以简单地创建一个看起来像按钮的非提交元素,并在单击时触发 a submit()

于 2013-09-05T21:00:56.377 回答