Click Radio Buttons in Materialize Using Selenium WebDriver
How to use Selenium WebDriver to click Materialize's transformed radio buttons
Materialize is a web design framework based on Material Design. While Materialize is not popular as BootStrap or Tailwind, it is still quite commonly used.
In this article, I will walk through how to click a Materialize radio button — warning, it’s not as straightforward as it looks!
Here’s an example Materialize radio button used in WhenWise. You can have a play with sample Materialize radio buttons here on their website.
The HTML fragment for the “Service” radio button is:
Beginner automated testers will think “that is easy”, and try with the following script statement (using the ID attribute is_service_true
):
driver.find_element(:id, "is_service_true").click
However, you will get this error:
Selenium::WebDriver::Error::ElementClickInterceptedError:
element click intercepted: Element is not clickable at point (481, 138). Other element would receive the click: ...
(Session info: chrome=138.0.7204.50)
Why? Because the radio buttons in Materialize are transformed with JavaScript. You can tell they are rendered differently from the normal radio buttons, right? As a result, the root radio element is now hidden.
<label>
<input type="radio" id="is_product_true" name="product[is_service]"
value="false" onclick="$('#custom_service_category').hide(); ">
<span style="font-size: 1.2rem">Product</span>
</label>
So, then how to automate the button?
Easy, instead of clicking the button, click the label next to the radio button, i.e., “Product” or “Service”. We can do this using Selenium’s XPath locator.
driver.find_element(:xpath, "//input[@id='is_product_true']/../span").click
sleep 0.25
I added sleep 0.25
, just to be safe, to allow the JavaScript operation to complete.
XPath Explanation — The
span
element contains the text label (e.g. “Product” or “Service”). However, the span does not have a unique identifier.
Instead, have XPath start at the Radio button which has a unique ID (//input[@id='is_product_true']
). Since span is next to the radio button, go up to the parent (/..
), then go down to the span element(/span
).
Related reading:
Web Test Automation with Selenium Case Studies (on Medium)