javaselenium-java

get items in radio buttons


I have this html code:

<div _ngcontent-ilf-c195="" class="datex-form-field">
   <!---->
   <mat-radio-group _ngcontent-ilf-c195="" role="radiogroup" class="mat-radio-group ng-pristine ng-valid ng-star-inserted ng-touched" id="searchType.toggle">
      <mat-radio-button _ngcontent-ilf-c195="" class="mat-radio-button datex-radiobutton mat-radio-checked mat-accent ng-star-inserted" id="mat-radio-5"><label class="mat-radio-label" for="mat-radio-5-input"><span class="mat-radio-container"><span class="mat-radio-outer-circle"></span><span class="mat-radio-inner-circle"></span><input type="radio" class="mat-radio-input" id="mat-radio-5-input" name="mat-radio-group-3" value="0" tabindex="0"><span mat-ripple="" class="mat-ripple mat-radio-ripple mat-focus-indicator"><span class="mat-ripple-element mat-radio-persistent-ripple"></span></span></span><span class="mat-radio-label-content"><span style="display: none;">&nbsp;</span>Shipment</span></label></mat-radio-button>
      <mat-radio-button _ngcontent-ilf-c195="" class="mat-radio-button datex-radiobutton mat-accent ng-star-inserted" id="mat-radio-6"><label class="mat-radio-label" for="mat-radio-6-input"><span class="mat-radio-container"><span class="mat-radio-outer-circle"></span><span class="mat-radio-inner-circle"></span><input type="radio" class="mat-radio-input" id="mat-radio-6-input" name="mat-radio-group-3" value="1" tabindex="-1"><span mat-ripple="" class="mat-ripple mat-radio-ripple mat-focus-indicator"><span class="mat-ripple-element mat-radio-persistent-ripple"></span></span></span><span class="mat-radio-label-content"><span style="display: none;">&nbsp;</span>Work Order</span></label></mat-radio-button>
      <!---->
   </mat-radio-group>
   <!---->
</div>

I tried to get the items under the tag mat-radio-group using this code:

List<WebElement>list = driver.findElements(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id=\"searchType.toggle\"]"));
list.get(1).click();

But I get java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 Can you advise how I can click on the second radio button?


Solution

  • The element mat-radio-group[@id="searchType.toggle"] is the radio button group (only present once in the page).

    Once you get it, you can select the radio options ("Shipment" and "Work Order") by using a child selector ./mat-radio-button:

    WebElement radioButtonGroup = driver.findElement(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id=\"searchType.toggle\"]"));
    List<WebElement> radioButtons = radioButtonGroup.findElements(By.xpath("./mat-radio-button"));
    radioButtons.get(1).click();