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?
This question is related to
java
selenium
attributes
checkbox
nullpointerexception
For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):
NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the !
sign at the beginning of the statement.
if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected())
{
driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}
I would do it with cssSelector:
// for all checked checkboxes
driver.findElements(By.cssSelector("input:checked[type='checkbox']"));
// for all notchecked checkboxes
driver.findElements(By.cssSelector("input:not(:checked)[type='checkbox']"));
Maybe that also helps ;-)
Lets assume
private string isChecked;
private webElement e;
isChecked =e.findElement(By.tagName("input")).getAttribute("checked");
if(isChecked=="true")
{
}
else
{
}
Hope this answer will be help for you. Let me know, if have any clarification in CSharp Selenium web driver.
The mechanism of selenium framework:
Here selenium make request to the its server and fetch first subelement with tagname input
WebElement e = e.findElement(By.tagName("input"));
Than you try to receive attribute on that element
object attribute = e.getAttribute("checked")
So either use
findElement(By.attribute("checked")
or use
findElement(By.xpath("\\input[@checked='true']")
P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.
public boolean getcheckboxvalue(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
return webElement.isSelected();
}
if(checkBox.getAttribute("checked") != null) // if Checked
checkBox.click(); //to Uncheck it
You can also add an and
statement to be sure if checked is true.
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}
Source: Stackoverflow.com