How can i handle radio button?



  • this is backend code for radio button

    <div>
      <input type="radio" name="notification_pref" title="" value="1" 
      class="notifyRadio" checked=""><p>By Email</p>
    </div>
    
    <div>
      <input type="radio" name="notification_pref" title="" value="2" 
      class="notifyRadio"><p>By Text Message - Message and Data Rates May 
      Apply</p>
    </div>
    

    How can I handle this radio button?



  • You work with radio buttons like you would work with a regular WebElement.

    1. Locate the element: WebElement myRadio = driver.findElement(By.xpath("//input[@type='radio'][@value='1']"));
    2. Perform a click: myRadio.click();

    The code above locates your first radio-button and selects it.

    UPD: There are a number of approaches that you can use to skip selection of already selected buttons (which one to use depends on your particular need). For example you can take all radio-buttons:

    List<WebElement> allButtons = driver.findElements(By.xpath("//input[@type='radio']"));
    

    and then iterate over the list to click first unselected button:

    for(WebElement button: allButtons){
        if(!button.isSelected()){
            button.click();
            break;
        }
    }
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2