Select CheckBox & Radio Button in Selenium WebDriver: In this automation world, its quite common that when you are trying to automate Web Form that time, you can see that a web form contains Checkboxes and Radio buttons. These elements enhance the functionality of the web page by providing facilities like selecting single and multiple values.
Until this tutorial, we have seen how we can locate the various type of elements with the help of different locator strategies. Still, in this tutorial, we are going to learn how we can perform operations on Checkboxes and radio buttons. There are few new operations we need to verify on these two elements like is the checkbox is already checked, or the radio button is already selected and verify their default states.
How to Select CheckBox & Radio Button
We can try to learn the various possible ways to select the elements with real-time examples and also verify the current status. So that you can understand easily.
Read Also: Selenium Wait Commands
For Selecting any element (Check Box / Radio button) you need to click on the element, so the command for this operation it looks like below:
// Java code example to select checkbox/radio button. WebElement target = driver.findElement(By.id("checkbox1")); target.click();
How to Check the state by IsSelected()
Sometimes before doing any action, we need to check the state of the Radio button or checkbox, and according to their state, we decide what operation we have to perform. So to verify the state of the element, we can use the IsSelected() method. When we execute the IsSelected() method, it will return a boolean value like true or false. Based on that, we can get to know the state of the element like if it is true, then that means the element is selected, and if it is false, then that means that specific element is not selected.
It’s better to verify a few things before performing any operation on the elements, like:
- If Radio button or Checkbox is displayed on the webpage
- If Radio button or Checkbox is enabled on the webpage
- Check the default selection of the Radio button or Checkbox
We can verify these things as mentioned earlier with the help of the below-predefined methods in selenium webdriver:
isDisplayed(): This method returns a boolean value. if it returns true, then said radio button is present on the webpage, or it returns False.
WebElement eleBtn = driver.findElement (By.id("testing")); eleBtn.isDisplayed();
isEnabled(): This method return an boolean value. if it returns true, then said radio button is present on the webpage, or it returns False.
WebElement eleBtn = driver.findElement (By.id("testing")); eleBtn.isEnabled;
isSelected(): This method return an boolean value. if it returns true, then said radio button is present on the webpage, or it returns False.
WebElement eleBtn = driver.findElement (By.id("testing")); eleBtn.isSelected();
Need to add more example and explanation