Jonathan
Jonathan

Reputation: 395

Check State of check box as checked or Not?

I am trying to verify if the state of a check box is checked or not if the state is false click if not do something else. Should i use .getAttribute() or .getState(). I think I should use get state.

 WebElement checkbox = driver.findElement(By.name("companyOptionsForm:mandateVerificationTotals"));

     if (checkbox.getState() == true) {
      //do something
     } else if (checkbox.getState()== false) {
      //do something
     }

The HTML of the Check box

< input name = "companyOptionsForm:mandateVerificationTotals"
type = "checkbox"role = "checkbox"aria - checked = "true"
class = "dijitReset dijitCheckBoxInput"data - dojo - attach - point = "focusNode"
data - dojo - attach - event = "ondijitclick:_onClick"
value = "on"tabindex = "0"id = "mandateVerificationTotals"
checked = "checked" style = "user-select: none;" >

However when i use .getState() eclipse shows a red line under it.

Upvotes: 1

Views: 2620

Answers (3)

arthur
arthur

Reputation: 3325

do something like this:

WebElement checkbox = driver.findElement(By.name("companyOptionsForm:mandateVerificationTotals"));

if (checkbox.isSelected()) {
  //do something
 } else  {
  //do something else
 }

Upvotes: 2

Fenio
Fenio

Reputation: 3625

You can also use javascript to verify if checkbox is selected

public boolean isChecked(WebElement element) {
    return (boolean) ((JavascriptExecutor) driver).executeScript("return arguments[0].checked", element);
}

Upvotes: 1

FredK
FredK

Reputation: 4084

An AWT Checkbox has a method called getState(), but not a method called isSelected().

A Swing JCheckBox has a method called isSelected(), but not one called getState().

And as @Arthur showed, do not compare a boolean to true of false; just use if (booleanVariable) or if (!booleanVariable)

Upvotes: 2

Related Questions