How can I check the checkboxes using an id or XPath expression? Is there a method similar to select by visibletext for a dropdown?
Going through the examples given for all other related questions, I could not find a proper solution that works in a concise way that by few line or method I can check a chekbox or radio button.
A sample HTML section is below:
<tbody> <tr> <td> <span class="120927"> <input id="ctl00_CM_ctl01_chkOptions_0" type="checkbox" name="ctl00$CM$ctl01$chkOptions$0"/> <label for="ctl00_CM_ctl01_chkOptions_0">housingmoves</label> </span> </td> </tr> <tr> <td> <span class="120928"> <input id="ctl00_CM_ctl01_chkOptions_1" type="checkbox" name="ctl00$CM$ctl01$chkOptions$1"/> <label for="ctl00_CM_ctl01_chkOptions_1">Seaside & Country Homes</label> </span> </td> </tr> </tbody>
We can select the checkbox with Selenium. In an html document, each checkbox has an attribute type set to a value as checkbox. In order to select a checkbox, we shall first identify a checkbox with any locator and then apply the click() method to it.
Selecting a checkbox is similar to clicking a button.
driver.findElement(By.id("idOfTheElement")).click();
will do.
However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.
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