How can i check a checkbox in Selenium Webdriver with Java?


How can i check a checkbox in Selenium Webdriver with Java?



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


boolean isChecked = driver.findElement((By.xpath(xpath1))).isSelected();



But this code returns incorrect value. The checkbox in the HTML:



Active checkbox







Inactive checkbox







How can I solve this problem in Selenium WebDriver with Java? Will be grateful for any help.




4 Answers
4



you can't use isSelected() because it is not a standart html input element.
my suggested solution is: you can take class attribute and check with active one:


if(driver.findElement((By.xpath(xpath1))).getAttribute('class') == 'ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active')
return True
else
return False



The issue is mainly because the checkbox that you have created is not a standard input checkbox element that html has, but a custom one. In order to check it, you can perform a click operation on it and see if it works.


driver.findElement(By.cssSelector('div.ui-chkbox-box)).click(); //check the checkbox



In order to verify whether its checked, you can verify the class of the element which adds ui-state-active to the div element when its active. Here's how -


ui-state-active


try{
driver.findElement(By.cssSelector('div.ui-state-active')); //find the element using the class name to see if it exists
}
catch(NoSuchElementException e){
System.out.println('Element is not checked');
}



Or get the class attribute of the element and then use it to see if it exists.


driver.findElement(By.cssSelector('div.ui-chkbox-box')).getAttribute('class');



Hope it helps.





On the page has more than 10 checkbox same attribute.
– Milky
Sep 25 '15 at 9:13



I managed to solve, but it is not too pretty solution:


String a = driver.findElement((By.xpath(xpath1))).getAttribute("class");
System.out.print(a.contains("ui-state-active"));



For more tricky situations
check boxes have a sudo css selector "checked"
So what you can do is add checked to your css selector like this


let check = !!driver.findElement({css:"div.ui-chkbox-box:checked"});






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages