I have a form with input
fields which can be added or removed dynamically. All my inputs are
name='first_name[]'
How i can fill in all my inputs?
If you are just inputting anything into each input, you can get a collection of all matching elements using all
. Then you can iterate over each to input them.
all_matching_inputs = page.all(:fillable_field, 'first_name[]')
all_matching_inputs.each{ |e| e.set('text') }
If you need to input specific ones, then there are a couple of solutions.
If the only thing unique about the input field is their position, they you could find all input fields and then select one by position:
# Set the first match
page.all(:fillable_field, 'first_name[]').first.set('text')
# Set the third match (note 0-based index)
page.all(:fillable_field, 'first_name[]')[2].set('text')
# Set the last match
page.all(:fillable_field, 'first_name[]').last.set('text')
Alternatively, you could use a css-selector (or xpath selector). However, it is a bit harder to read:
# Set the second match (note 1-based index)
page.find('input[name=first_name\[\]]:nth-of-type(2)').set('text')
It is rare that there is nothing unique about the element (input) you want to find. Usually there is some element around it that is related and unique (ie there must be something else on the page that, as a user, you are using to differentiate it from others).
For example, in the following html:
<div>
<span>User1</span>
<input name='first_name[]'>
</div>
<div>
<span>User2</span>
<input name='first_name[]'>
</div>
There are two input fields with the same name. However, they can be distinguished based on their related sibling span, which tells the user the input is related to.
In this case, you can find the span, go to the parent div, and then locate the input within the scope of that div. Essentially, this is finding the input based on the user.
page.find('span', :text => 'User2').find(:xpath, '..').fill_in('first_name[]', :with => 'text')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With