Set styled radio buttons and checkboxes that have hidden or overlapped the input field

Problem

There seems to be an upward trend in applications using label elements to style radio buttons and checkboxes. This can cause issues when Watir tries to set the field. For example:

These issues can be reproduced on the following page:

<html>
  <body>
    <div>  
      <input type="checkbox" id="overlapped_checkbox" style="position:absolute;">
      <label for="overlapped_checkbox" style="background-color:white; position:relative;">Label for overlap<label>
    </div>      
    <div>
      <label for="hidden_radio">Label for hidden</label> 
      <input type="radio" id="hidden_radio" style="display:none;">    
    </div>
  </body>
</html>

With the following Watir code:

browser.checkbox(id: 'overlapped_checkbox').set
#=> Selenium::WebDriver::Error::UnknownError:
#=>   Element is not clickable at point (18, 17). 
#=>   Other element would receive the click: <label for="overlapped_checkbox" style="background-color:white; position:relative;">...</label>

browser.radio(id: 'hidden_radio').set
#=> Watir::Exception::UnknownObjectException:
#=>   element located, but timed out after 30 seconds, 
#=>   waiting for true condition on #<Watir::Radio: located: true; {:id=>"hidden_radio", :tag_name=>"input", :type=>"radio"}> 

How do you get Watir to set these fields?

Solution

With these styled controls, a user never actually interacts with the input field. They only see and click the label element, which might happen to include an image of an enabled/disabled field. This works because the browser transfers clicks on the label element to clicks on the input field.

Watir needs to do the same thing as a user – ie click the label element instead:

p browser.checkbox(id: 'overlapped_checkbox').checked?
#=> false
browser.label(for: 'overlapped_checkbox').click
p browser.checkbox(id: 'overlapped_checkbox').checked?
#=> true

p browser.radio(id: 'hidden_radio').set?
#=> false
browser.label(for: 'hidden_radio').click
p browser.radio(id: 'hidden_radio').set?
#=> true
Advertisements
This entry was posted in Watir, Watir-Webdriver and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s