Tomasz Wida
Tomasz Wida

Reputation: 359

Selenium Webdriver capture Checkbox text

Hello I'm trying to capture the name next to the checkbox that is in the same span class but the name is located in the label tag. when trying to capture text using the getText() method, I'm getting empty name.

to show it in the code How I'm doing it.

//to find the checkbox
@FindBy(how = How.ID, id = "ConstructionManagement")
private WebElement constructionMgmnt;

when Using this getText but I'm getting empty text. when using getAttribute I'm getting the actual name of the Checkbox with is $PpyWorkPage$pOutageRequest$pConstructionManagement

constructionMgmnt.getText();
constructionMgmnt.getAttribute("name")

The page source how checkbox is coded.

<span class="checkbox" data-ctl="Checkbox">
   <input value="false" name="$PpyWorkPage$pOutageRequest$pConstructionManagement" type="hidden">
   <input id="ConstructionManagement" class="checkbox chkBxCtl" value="true" name="$PpyWorkPage$pOutageRequest$pConstructionManagement" validationtype="true-false" pn=".ConstructionManagement" type="checkbox">
   <label class=" cb_standard" for="ConstructionManagement">Construction Management</label>
</span>

Can anyone think of how to grab to get the text from the element that is pointing to the Checkbox ID, or I have to Use the the xpath to label to get the text next to that checkbox?

//example of garbing the name of the Label (I tested this and it works)
driver.findElement(By.xpath("//label[@for='ConstructionManagement']"));

Thank you.

Upvotes: 1

Views: 1539

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

Use the following code to locate the Label:

//to find the Label Text
@FindBy(how = How.ID, xpath = "//input[@id='ConstructionManagement')//following::label[1]"
private WebElement constructionMgmnt_label;

Next you can use the following to retrive the Checkbox Text as follows:

String my_label = constructionMgmnt_label.getAttribute("innerHTML")

Upvotes: 2

Related Questions