Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tell if a checkbox is selected in Selenium for Java?

I am using Selenium in Java to test the checking of a checkbox in a webapp. Here's the code:

private boolean isChecked; private WebElement e; 

I declare e and assign it to the area where the checkbox is.

isChecked = e.findElement(By.tagName("input")).getAttribute("checked").equals("true"); 

What is weird is that getAttribute("checked") returns null and therefore a NullPointerException

In the HTML for the checkbox, there is no checked attribute displayed. However, isn't it the case that all input elements have a checked = "true" so this code should work?

like image 671
jamesfzhang Avatar asked Nov 18 '11 19:11

jamesfzhang


People also ask

How can we check if a checkbox is selected or not?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Which method is used to check the status of checkbox?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.

Which method is used to check if an element is selected or not?

is_selected method is used to check if element is selected or not. It returns a boolean value True or False.It can be used to check if a checkbox or radio button is selected.

Which method is used to select a checkbox in Selenium?

We can select a checkbox either by using the click() method on the input node or on the label node that represents the checkbox. Selenium also offers validation methods like isSelected, isEnabled, and isDisplayed.


2 Answers

If you are using Webdriver then the item you are looking for is Selected.

Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.

So what you would look for in Selenium Webdriver is this

isChecked = e.findElement(By.tagName("input")).Selected; 

As there is no Selected in WebDriver Java API, the above code should be as follows:

isChecked = e.findElement(By.tagName("input")).isSelected(); 
like image 132
CBRRacer Avatar answered Oct 07 '22 18:10

CBRRacer


if ( !driver.findElement(By.id("idOfTheElement")).isSelected() ) {      driver.findElement(By.id("idOfTheElement")).click(); } 
like image 20
ShutterSoul Avatar answered Oct 07 '22 18:10

ShutterSoul