1

I have 3 checkboxes on the webpage. Each time, I want to select checkboxes randomly.

4

You can use findElements to have a list of checkboxes then you simply have to pick a random element:

List<WebElement> checkboxes = driver.findElements(By.cssSelector(".myCheckboxClass"));

WebElement randomCheckbox = checkboxes.get(new Random().nextInt(list.size()));

Note: It assumes some element will be found by the locator - if no element is found, an IndexOutOfBoundsException is raised.

0

You can use the below method code:

public void clickonRandomCheckBox()
{
    List<WebElement> checkboxes = driver.findElements(By.xpath("//input[@type='checkbox']"));
    Random ram=new random.nextInt(1,3);
    if(!checkboxes.get(ram).isSelected)
    {
        checkboxes.get(ram).click();
    }
}
  • 1 - It is not valid Java code. 2 - The code does not "click on a random checkbox", it "UNSELECTS a random checkbox IF IT IS SELECTED, otherwise, it DOES NOTHING" – João Farias Sep 12 at 12:01
  • first of all it's a valid code .Please check your knowledge level isSelected() return true if checkbox is selected else its return false i have apply the not operation here .Go and Do the RnD – viren tiwari Sep 13 at 6:50
  • Although the reply was quite unfriendly (already reported), I will point out the errors: "new random" is not syntacticly correct; "new Random()" would be the case. Random.nextInt returns an int, not a Random. – João Farias Sep 13 at 6:56
  • Additionally, as you said, the code, when corrected would result in a NoOP if the randomly choosen is already selected. The question is asking how to select a checkbox. Not selecting anything is not, by definition, selecting something. The code implies additional behavior not asked on the question. – João Farias Sep 13 at 6:59
  • Both of you need to calm down. You are both right, and both wrong. In Java and C#, you need to call new Random(). In Java, you would need to use nextInt(3) to correctly choose a random integer to select one of the checkboxes. In C#, the equivalent is Next(3). You could also use Next(0, 3). Both of you have missed that Java uses 0-based indexing, so as soon as the random generator returns 3, the code will throw an index out of bounds exception. The question asks how to select, so if something is already selected, it is selected and needs no more action. Viven, you could update (...cont) – Kate Paulk Sep 13 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.