Reputation: 5549
I have the following helper method to input a string into an input field and press the enter key, but it seems the enter key is never pressed. I see the string entered into the input field, but the events that take place upon hitting enter never happened.
I've tested in an actual browser that the enter key correctly fires the expected events. I'm not sure what I'm missing.
def fill_and_trigger_enter_keypress(selector, value)
page.execute_script %Q(
var input = $('#{selector}');
input.val('#{value}');
input.trigger("keypress", [13]);
)
end
EDIT:
I've also tried the following to no avail:
find('#q_name').native.send_keys(:return)
find('#q_name').native.send_keys(:enter)
They don't cause any error, but still no enter key pressed.
Upvotes: 73
Views: 37563
Reputation: 10083
Use fill_in
as usual, but append a newline character "\n"
to the with:
value. The with:
value must be in double quotes, not single quotes. This will trigger a form submission:
fill_in "q_name", with: "hello world\n"
Upvotes: 2
Reputation: 9644
These days (Capybara version 2.5+) you can simulate the <enter>
key in the following way:
find('.selector').set("text\n")
The \n
(new line) is the very important bit here.
Upvotes: 37
Reputation: 11
@Page.selector.send_keys :return
This works for me, where selector
is the element in your page object
element :selector, '<css selector>'
Upvotes: 0
Reputation: 185
It works for me
page.execute_script("$('form.css-class/#form_id').submit()")
Upvotes: 1
Reputation: 1737
find('#q_name').native.send_keys(:return)
works for me. I dont have a name or id for my field but the type is input so i used something like
find('.myselector_name>input').native.send_keys(:return)
works perfectly fine!
Upvotes: 94
Reputation: 10750
Usually when you run page.execute_script, you get the same results as if you were running that in the page console. Try running that manually in the console and see if you get the expected results. That is usually what I do.. craft the needed js code in the browser console window and paste it into the capybara code when it is working, using execute_script.
Upvotes: 6
Reputation: 17470
Capybara doesn't have native support for a send_keys type event. You might be able to go down to selenium to do it, or you can try this gem https://github.com/markgandolfo/send-keys
Upvotes: 5