Handling RadioButtons in selenium

On a webpage, user can only selects one option from many of the limited group of options.

In HTML we can represent a radio button with tag name "input" and attribute type="radio".
Let's see the code implementation

package controls;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Radiobuttons {

public static void main(String[] args) throws InterruptedException {
 WebDriver driver=new FirefoxDriver();
 driver.manage().window().maximize();
 driver.get("http://www.qavalidation.com/p/demo.html");

 WebElement val=driver.findElement(By.name("experience"));
 List<webelement> radios = val.findElements(By.xpath("//input[@type='radio']"));
 System.out.println("No. of radio buttons: "+radios.size());
 for(WebElement radio: radios)
       {
        if(radio.getAttribute("value").equals("four"))
     radio.click();
     System.out.println(radio.getAttribute("value")+"---"+radio.getAttribute("checked"));
     //System.out.println(radio.getAttribute("value")+"---"+radio.isSelected());
    } 
   }
}
/*
radio.getAttribute("checked") will return true or null
radio.isSelected() will return true or false
*/

No comments:

Post a Comment