How to find a field using placeholder text in Watir?

1.2k Views Asked by At

I have two search fields and I want to find the second one to set some text.

I have tried using div however it always finds the first search field. Does anyone one have a suggestion on how to find the second object or use the unique placeholder text "Search..." ?

HTML:

input type="text" name="searchString" id="searchString" projects="" for="" placeholder="Search" class="form-control"
input type="text" name="searchString" id="searchString" placeholder="Search..." class="form-control"

Ruby - Watir:

@b.link(:text => "http://ml-test.mytest.com/Client/Profile/ab295b41-2c5e-4100-bdee-e757405238bb").click
@b.text_field{div(:class => "col-sm-4 col-md-3", :placeholder => "Search...")}.set "Automation (Test)"
1

There are 1 best solutions below

2
On BEST ANSWER

It looks like the problem might simply be a typo in the code. Notice in the line:

@b.text_field{div(:class => "col-sm-4 col-md-3", :placeholder => "Search...")}.set "Automation (Test)"

That a block, seen by the {}, is being passed to the text_field method. The text_field method does not do anything with blocks, as a result the code is really just doing:

@b.text_field.set "Automation (Test)"

As there is no locator supplied to the text field, it will input the first text field on the page.

To locate the text field based on the placeholder attribute (or any other locator), it needs to be passed as an argument instead of a block:

@b.text_field(:placeholder => "Search...").set "Automation (Test)"

You had included a div as well. Assuming that it is an ancestor element need to find the text field, it should be:

@b.div(:class => "col-sm-4 col-md-3").text_field(:placeholder => "Search...").set "Automation (Test)"