Unable to click on checkbox using Selenium WebDriver



  • I am passing in the checkbox ID, grabbing the element and then if the checkbox is not checked I want to check it. It wouldn't check the box though, so I was debugging and then it worked when I added a second one in, so I added 2 to make it work and cleaned up some clutter I had created with commented code and such, then I ran it again and it didn't check the checkbox on either click. The funny thing is that I am getting focus on the checkbox.

    Could this be an issue when there are certain security measures in place for the code? Is there a workaround for this?

    Not sure if it matters but I am using XUnit for the testing framework.

    [Then(@"I check the '(.*)' checkbox")]
    public void ThenICheckTheCheckbox(string checkBoxId)
    {
        var checkBox = Ie.FindElementById(checkBoxId);
        var isChecked = checkBox.Selected;
    
        if (!isChecked)
        {
            checkBox.Click(); 
            checkBox.Click();
            isChecked = checkBox.Selected;
    
        }
        Assert.True(isChecked, $"the checkbox with id of: {checkBoxId}, is not checked");
    
    }
    

    The HTML for the checkbox is this

    <input class="check-box" data-val="true" data-val-required="The Is Active field is required." 
        id="IsActive" name="IsActive" type="checkbox" value="true">
    


  • Rather than accessing the element by Id try doing it with xpath. I can see the there is an tag attached to this element. So you could make use of that.So for example if your checkbox is setup like this:

    <div id = "divContainer">
    <input class="check-box" data-val="true" data-val-required="The Is Active 
     field is required." 
    id="IsActive" name="IsActive" type="checkbox" value="true">
     </div>
    

    Then you can use something like this:

     bool selected 
     =driver.findElemeny(By.xpath(.//[@id='divContainer']/input)).isSelected();
    

    And then you can make use of the selected variable to click or unclick the checkbox. If you could provide me with the full page's code then I will be able to write the full xpath for you



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2