user081608
user081608

Reputation: 1113

Enter text in input in Watir with same class

I am trying to enter text into an input field and can not successfully get it working. I have two inputs that look like this:

<div class"outerParentClass">
    <div class="classLabel">From</div>
        <div class="classA classB classD">
            <div class="classE">
               <div class="classText"> TEXT HERE </div>
               <input class="classInputA classInoutB" type="text">
           </div>
       </div>
   </div>
   <div class="classLabel">To</div>
        <div class="classA classB classD">
            <div class="classE">
               <div class="classText"> DIFFERENT TEXT HERE </div>
               <input class="classInputA classInoutB" type="text">
           </div>
       </div>
   </div>
</div>

Both the inputs are the exact same format as above. There are no Id's and both have the same classes. I am struggling at entering the text into these or even finding them correctly.

When I do this:

browser.text_field(:class => "classInputA").size

It returns 20

When I do this:

browser.text_field(:class => "classInputA")

It returns:

#<Watir::TextField:0x..fbccafb7ed2e9b85e located=false selector={:class=>"classInputA", :tag_name=>"input"}>

Not sure how to locate either of these inputs. Any suggestions?

Upvotes: 1

Views: 520

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

The text adjacent to the field provides a label and context for the field. As it is likely unique, you can use this to identify the element.

To do this, find the div containing the label text. Then navigate to the adjacent div that contains the text field.

browser.div(text: 'From', class: 'classLabel') # label of interest
  .element(xpath: './following-sibling::div[1]') # adjacent div containing text field
  .text_field # the text field

Note that in the next release of Watir, .element(xpath: './following-sibling::div[1]') will be replaceable by just .following-sibling.

Upvotes: 2

Related Questions