Run time error while typecasting WebDriver to CheckBox
In my application, I have a grid with a column for check boxes. The ID of the check boxes for each row differs only by the number after a fixed value. xxxx_0, xxxx_1, ....
In order to select a check box in any row, the row number can be appended to get the complete ID.
My code is like this :
for(int i=0; i<10; i++) {
CheckBox visible = (CheckBox) driver.findElement(By.id("visibleCheckboxValue_" + i));
visible.toggle(false);
}
This gives me a run time error as "cannot cast Remote webdriver to CheckBox."
Also, if I use cast it as WebElement
, I cannot use the toggle(boolean select)
function.
for(int i=0; i<10; i++) {
WebElement visible = (WebElement) driver.findElement(By.id("visibleCheckboxValue_" + i));
if(visible.isSelected()) {
visible.click() // To uncheck the check box
}
}
On a WebElement
, I can use .isSelected()
to check if the check box is selected or not, but it always returns false. Even if the check box is selected, it returns false.
Is there any way to cast a Webdriver to CheckBox, so I can use the toggle()
function effectively ?
Well you are thinking about this the wrong way around.
You are not going to be able to cast it to a CheckBox
, and I wouldn't expect you to! That's integrating with another API, which Selenium does not do! You shouldn't be casting the result from .findElement()
at all!
You need to think about why you are unable to use the inbuilt functionality and not about how you can mangle it into a different object.
The first thing I would suggest is to explicitly check the "checked" value of the element you are bringing back.
When a checkbox
is checked
in HTML, it can be set in a various amount of different ways, see this StackOverflow question regarding the "right" way to set a checkbox to checked
. Here, you should be able to see it isn't a simple case of yes
or no
.
So check what value the checked
status is, on that element. I'm not going to do it for you, that's not the point of learning, but psuedo-code:
WebElement checkBox = driver.findElement(driver.findElement(By.id("visibleCheckboxValue_" + i));
string checkedStatus = checkBox.getAttribute("checked");
// now do some checking...ie. does that string now contain something? yes? it's checked.
Now you should be able to use the .isSelected
method, but before we go any further, see if the above works. If so, great, but it means something is broken elsewhere. If not then you should also provide your HTML (with any accompanying JS and CSS that may be relevant) so we can effectively diagnose this issue with you.