How to handle Checkbox in Selenium | BrowserStack (2024)

What is a Checkbox?

Checkbox, also known as Selection box or tick box is a small interactive box on a web page that allows a user to select one or more options. On selecting the checkbox, a tick mark is displayed inside the checkbox indicating that the particular option is selected. To deselect a checkbox user may simply click on the checkbox to deselect the already selected option. It facilitates the user to select single or multiple options from a list of choices and the web page may remember it for future use.

When working in web automation, like any other web element such as input box, button, links, checkbox should also be automated. Let us deep dive to understand how we can do that with the help of Selenium.

Table of Contents

  • What is a Checkbox?
  • How to handle Checkbox in Selenium?
    • Selecting Checkbox in Selenium
  • How to Select multiple options in Checkbox using Selenium
  • How to assert that a checkbox is checked?
  • How to Deselect Checkbox in Selenium
  • How to handle Checkbox in Selenium?

    Before jumping to how to select/deselect a checkbox on a web page using Selenium, let us first learn how to locate a checkbox using Selenium. Selenium offers various locator strategies and almost all of them can be used to locate a check box. Let us see some one of them with an example.

    Using W3Schools website to demonstrate locating checkboxes on web pages using Selenium.

    How to handle Checkbox in Selenium | BrowserStack (1)

    Click on “Try it Yourself button” to land to
    https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox

    (Note: If the above practice page appears broken for you, you may simply search “w3schools checkbox” on Google.com to get the desired practice web page)

    Locate checkbox using Id locator

    If a checkbox element has an id attribute which is unique, we can use the ID locator of Selenium WebDriver to locate a checkbox. A checkbox in the DOM is defined using the input tag with the type as ‘checkbox’.

    Example:

    <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">

    How to handle Checkbox in Selenium | BrowserStack (2)

    You can see from the above image that the “I have a bike” checkbox has an input tag with type=’checkbox’ and id=’vehicle1’. If we need to locate this checkbox with ID locator below would be the Selenium code:

    WebElement bike=driver.findElement(By.id("#vehicle1"));

    Selecting Checkbox in Selenium

    To select any checkbox we need to use the click() method of the WebElement interface of Selenium.

    bike.click();

    After the click operation, the checkbox should appear to be selected as shown in below image:

    How to handle Checkbox in Selenium | BrowserStack (3)

    Locate checkbox using name locator

    If a checkbox element has a name attribute which is unique, we can use the name locator of Selenium WebDriver to locate a checkbox.

    You can see from the above image that the “I have a bike” checkbox has the name=’vehicle1’. If we need to locate this checkbox with name locator below would be the Selenium code:

    WebElement bike=driver.findElement(By.name("vehicle1"));

    To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

    bike.click();

    Locate checkbox using XPath locator

    Sometimes Selenium cannot find a checkbox with just the id or name value or any other attribute, and therefore XPath is considered in such cases.

    You can see from the above image that the “I have a bike” checkbox has an input tag with name=’vehicle1’ and id = ‘vehicle1’. If we need to locate this checkbox with XPath locator below would be the Selenium code:

    WebElement bike=driver.findElement(By.xpath("//input[@name='vehicle1' and @id='vehicle1']"));

    To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

    bike.click();

    Locate checkbox using CSSSelector

    Like XPath, CSSSelector can also be used if Selenium cannot find a checkbox with just the id or name or any other attribute value.

    You can see from the above image that the “I have a bike” checkbox has an input tag with type=’checkbox’, id = ‘vehicle1’. If we need to locate this checkbox with CSSSelector locator below would be the Selenium code:

    WebElement bike=driver.findElement(By.cssSelector ("input#vehicle1"));

    To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

    bike.click();

    Locate checkbox using Attribute value

    Sometimes a group of checkboxes may have the same name or class or id value, which makes it difficult to check a single checkbox. In such cases, checkboxes can be located by using their value attribute as each checkbox has a unique value assigned to it.

    How to handle Checkbox in Selenium | BrowserStack (4)

    If we need to locate “I have a bike” checkbox with value attribute we can use CSSSelector and below would be the Selenium code:

    WebElement bike=driver.findElement(By.cssSelector("input[value='Bike']"));

    To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

    bike.click(); 

    How to Select multiple options in Checkbox using Selenium

    In the above example, we learned that in some web pages, there may be a group of checkboxes which have the same name/class/id attribute and therefore choosing the checkbox with respect to their value attribute is the best option if we need to click on a single checkbox.

    And if there is a need to select multiple checkboxes which have the same name/id/class attribute but different attribute values, creating different web elements and then clicking on it one by one would be cumbersome. Instead we can create a list of web elements and iterate through it sequentially and click on it.

    Let us see how we can select all checkboxes in the above example with the below Selenium code.

    • First, we will create a List of web elements to store all the checkboxes.
    List<WebElement> chkboxes=driver.findElements(By.cssSelector("input[type='checkbox']"));
    • Then we need to find out the size of the web element list.
    int size=chkboxes.size();
    • Then using the for loop and get() method we will iterate through all the check boxes and click on it using the click() method.
    chkboxes.get(i).click();

    Complete code:

    public class CheckBox {public static void main(String args[]) { WebDriver driver=new ChromeDriver();driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox");  //Switch to the iframe which contains the checkboxesdriver.switchTo().frame("iframeResult"); List<WebElement> chkboxes=driver.findElements(By.cssSelector("input[type='checkbox']")); int size=chkboxes.size(); for (int i=0; i<size; i++) { chkboxes.get(i).click(); }}}

    Validations on a checkbox using Selenium

    To validate pre and post conditions of checkbox’s state, Selenium provides certain methods which are as follows:

    • isEnabled(): A pre-validation for checkbox click event to check whether the checkbox is enabled or disabled on the web page. This method returns true in case element is enabled otherwise it returns false.
    • isDisplayed(): A pre-validation for checkbox click event to check whether the checkbox is displayed on the web page or not. It returns true if the desired element is displayed on DOM otherwise it returns false.
    • isSelected(): A post-validation after the checkbox click event to check whether the checkbox is selected or not. It returns true if the element is selected, else false for deselected.

    Suppose there is a scenario where the user needs to first check the visibility of the checkbox and based on the visibility it needs to be selected. So in such a condition we can use isDisplayed() method as a precondition and on the basis of its result either true or false, the checkbox can be selected.

    public class CheckBox {public static void main(String args[]) { WebDriver driver = new ChromeDriver();driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox"); // Switch to the iframe which contains the checkboxesdriver.switchTo().frame("iframeResult"); WebElement car = driver.findElement(By.cssSelector("input#vehicle2")); System.out.println("car.isDisplayed()" + car.isDisplayed()); if(car.isDisplayed()==true) { car.click();  }else { System.out.println("Option is not displayed"); }}}

    How to assert that a checkbox is checked?

    If there is a need to validate whether the checkbox is selected after selecting the desired checkbox, we can use isSelected() method which returns true if the checkbox is selected and false in either case. The Selenium code to test this scenario is as follows:

    public class CheckBox {public static void main(String args[]) { WebDriver driver = new ChromeDriver();driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox"); // Switch to the iframe which contains the checkboxesdriver.switchTo().frame("iframeResult"); WebElement car = driver.findElement(By.cssSelector("input#vehicle2")); car.click();System.out.println("car.isSelected()" + car.isSelected()); if(car.isSelected()==true) { System.out.println("Option is selected"); }else { System.out.println("Option is not selected"); }}}

    How to Deselect Checkbox in Selenium

    At the start of this article we learnt that the click() method of WebElement interface is used to click a checkbox. Similarly, to deselect a checkbox, the same click() method is used.

    However, in web automation it is a good practice to check the state of the checkbox before deselecting it, otherwise clicking to deselect the checkbox will select the checkbox if the checkbox was not in a selected mode previously.

    public class CheckBox {public static void main(String args[]) { WebDriver driver = new ChromeDriver();driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox"); //Switch to the iframe which contains the checkboxesdriver.switchTo().frame("iframeResult"); WebElement car = driver.findElement(By.cssSelector("input#vehicle2")); //car.click();System.out.println("car.isSelected()" + car.isSelected()); if (car.isSelected()) { car.click(); System.out.println("Car deselected"); }else { System.out.println("Car is already deselected"); }}}

    Conclusion

    This article discussed how to locate a checkbox on a web page with different Selenium locator strategies, how to select and deselect it, and validate that the checkbox is selected or not. It is recommended that when testing the checkboxes on your testing web application you should test is on real devices and browsers for more accurate test results.

    Using BrowserStack’s real device cloud which provides 3000+ real devices and browsers you can test your web application comprehensively. It supports cross-browser testing and delivers a seamless user experience across browsers and devices.

    Try BrowserStack Now

    How to handle Checkbox in Selenium | BrowserStack (2024)
    Top Articles
    Does Closing Old Bank & Credit Card Accounts Affect Your Credit Score? | UK | Loqbox
    CoCalc -- blooks-table.html
    Craigslist Livingston Montana
    Chris Provost Daughter Addie
    Form V/Legends
    Women's Beauty Parlour Near Me
    Parks in Wien gesperrt
    Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
    Xm Tennis Channel
    Missing 2023 Showtimes Near Landmark Cinemas Peoria
    Regular Clear vs Low Iron Glass for Shower Doors
    Shariraye Update
    Mlb Ballpark Pal
    UEQ - User Experience Questionnaire: UX Testing schnell und einfach
    Ts Lillydoll
    Nwi Arrests Lake County
    Minecraft Jar Google Drive
    Costco Gas Foster City
    New Stores Coming To Canton Ohio 2022
    Troy Bilt Mower Carburetor Diagram
    Lazarillo De Tormes Summary and Study Guide | SuperSummary
    라이키 유출
    Craigslist Red Wing Mn
    Iu Spring Break 2024
    All Obituaries | Gateway-Forest Lawn Funeral Home | Lake City FL funeral home and cremation Lake City FL funeral home and cremation
    Greenville Sc Greyhound
    TeamNet | Agilio Software
    *!Good Night (2024) 𝙵ull𝙼ovie Downl𝚘ad Fr𝚎e 1080𝚙, 720𝚙, 480𝚙 H𝙳 HI𝙽DI Dub𝚋ed Fil𝙼yz𝚒lla Isaidub
    Isablove
    County Cricket Championship, day one - scores, radio commentary & live text
    Inmate Search Disclaimer – Sheriff
    Red Sox Starting Pitcher Tonight
    Kstate Qualtrics
    oklahoma city community "puppies" - craigslist
    Nearest Ups Office To Me
    Is The Nun Based On a True Story?
    Joey Gentile Lpsg
    Taylor University Baseball Roster
    Questions answered? Ducks say so in rivalry rout
    Dcilottery Login
    Ucsc Sip 2023 College Confidential
    Best Restaurants West Bend
    Umd Men's Basketball Duluth
    Lyndie Irons And Pat Tenore
    Fedex Passport Locations Near Me
    How to Install JDownloader 2 on Your Synology NAS
    Tropical Smoothie Address
    Conan Exiles Colored Crystal
    Joy Taylor Nip Slip
    Rovert Wrestling
    Diamond Desires Nyc
    login.microsoftonline.com Reviews | scam or legit check
    Latest Posts
    Article information

    Author: Foster Heidenreich CPA

    Last Updated:

    Views: 5991

    Rating: 4.6 / 5 (56 voted)

    Reviews: 87% of readers found this page helpful

    Author information

    Name: Foster Heidenreich CPA

    Birthday: 1995-01-14

    Address: 55021 Usha Garden, North Larisa, DE 19209

    Phone: +6812240846623

    Job: Corporate Healthcare Strategist

    Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

    Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.