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?
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.
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.
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.
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.
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();
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() ) { driver.findElement(By.id("idOfTheElement")).click(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With