95

I'd like to do the following but can't due to the nature of fill_in expecting a locator as the first argument.

find(:css, "input[id$='donation_pledge_hundreds']").fill_in :with => "10"

I've also tried doing

element = find(:css, "input[id$='donation_pledge_hundreds']")   
fill_in element.<method> , :with => "10"

but there are no methods that return any data to identify the element to fill_in.

Any ideas of the best way of finding a field via a regex for use with fill_in?

Kara
  • 6,115
  • 16
  • 50
  • 57
ants
  • 1,097
  • 1
  • 7
  • 13

5 Answers5

170

If you have a reference to the element itself you'd use set instead of fill_in:

find(:css, "input[id$='donation_pledge_hundreds']").set("10")

However for your specific example, fill_in should be able to find the element as you know it's ID:

fill_in 'donation_pledge_hundreds', with: "10"
user664833
  • 18,397
  • 19
  • 91
  • 140
Jon M
  • 11,669
  • 3
  • 41
  • 47
  • Good man, That's the one. That particular field is used in different contexts (authenticated/not authenticated) and so takes a different field id. donation_pledge_hundreds is the common part of the field id hence comparing the end of the field name $= – ants Dec 17 '11 at 12:33
  • 9
    Be careful using 'set' rather than the other built-in methods, as it doesn't trigger events after changing the value. – Dan Caddigan Feb 11 '14 at 00:12
  • @DanCaddigan and that's why it seems f3ck3d up :/ how do you do then ? – Ben Jan 29 '16 at 17:09
  • 2
    You can use `find(:css, "...").set("10").send_keys(:return)` to press return afterwards. It triggers the relevant events. I've not tested it but you can also `find(:css, "...").set("10").trigger(:blur)` if that's your thing. – gondalez Jun 19 '18 at 07:19
8
element = find(:css, "input[id$='donation_pledge_hundreds']")   
element.fill_in with: "10"
aki
  • 81
  • 1
  • 1
  • Code only answers are discouraged. Please add some explanation as to how this solves the problem, or how this differs from the existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/23104752) – Nick May 25 '19 at 04:41
  • This works well, thanks for letting us know you can omit the `within` part (i.e., the first argument). – Nitrodist Nov 23 '20 at 08:03
5

Instead of a method, you can use brackets to return :name or :id, e.g. element = find(:css, "input[id$='donation_pledge_hundreds']") fill_in element[:name], :with => "10" The same approach can be used with select - select my_type, from: find('select[name$="[type]"]')[:name]

bhfailor
  • 175
  • 2
  • 6
3
find("input[id$='donation_pledge_hundreds']").set "10"

It's worth noting that you can chain your finds.

@modal = find(".modal")
@modal.find('input[name=foo]').set "bar"
Nate
  • 12,963
  • 4
  • 59
  • 80
0
fill_in <$id>, :with => 'text you want to fill in'