Hasan Sarıkaya
Hasan Sarıkaya

Reputation: 11

c# selenium How to click on a checkbox

I would like to click a chechbox through C# and Selenium. The checkbox HTML is as follows :

<div class="ad-post-rules" ng-class="{'ad-post-rules-error': submitted &amp;&amp; addClassifiedForm.postRulesCheck.$error.required}" an-form-error="" an-form-error-optional-text="İlan verme kurallarını onaylamadınız."><input id="postRulesCheck" class="checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="checkbox" value="1" name="postRulesCheck" ng-model="postRulesCheck" required="" an-form-object-name="İlan Verme Kuralları"><label for="postRulesCheck"></label><span class="rulesOpen" ng-click="adPostRules=true">İlan verme kurallarını</span><label for="postRulesCheck">okudum, kabul ediyorum</label></div>

My code is as follows :

Dim cekbul As IWebElement
System.Threading.Thread.Sleep(1000)
cekbul = driver.FindElement(By.Id("#postRulesCheck"))
cekbul.Click()

Upvotes: 1

Views: 2425

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193088

To click on the checkbox as the element is an Angular element you have to induce WebDriverWait for the elelemt to be clickable and you can use either of the following option :

  • CssSelector :

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.checkBox.sg-checkbox.ng-pristine.ng-untouched.ng-empty.ng-invalid.ng-invalid-required#postRulesCheck"))).Click();
    
  • XPath :

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required' and @id='postRulesCheck']"))).Click();
    

Upvotes: 0

iamsankalp89
iamsankalp89

Reputation: 4739

I dont know coding in c sharp but i think it works

IWebElement Ele_CheckBox = driver.FindElement(By.Id("postRulesCheck"));

Ele_CheckBox.Click();

By using name

IWebElement Ele_CheckBox = driver.FindElement(By.Name("postRulesCheck"));

Ele_CheckBox.Click();

By xpath

IWebElement Ele_CheckBox = driver.FindElement(By.Xpath("//input[@id='postRulesCheck']"));

Ele_CheckBox.Click();

Upvotes: 1

Nish26
Nish26

Reputation: 987

Selenium can click only on element that is visible for a human. You can still execute javascript even if the element is not visible. If the element is visible for a human while you are trying to execute your test and still you are getting the element not visible exception , try to use Actions API instead otherwise use javascript.

 Actions action = new Actions(driver);
 IWebElement cekbul = driver.FindElement(By.Id("postRulesCheck"));
 action.Click(cekbul).Build().Perform();

This lets you click at a point irrespective of the location of point .

Upvotes: 0

Related Questions