What I\'m trying to do is click on (or off) any of the checkboxes on my page. As you can see from the HTML, each checkbox element would appear to have a unique identifier but w
Use the following CSS Selector for that:
.url-field-toggle[data-yesno-name='Url_Transaction_Out']
Code is:
driver.FindElement(By.CssSelector("url-field-toggle[data-yesno-name='Url_Transaction_Out']")).Click();
Hope it helps you!
Since you need to click the SPAN, e.g.
<span class="glyphicon clickable glyphicon-remove" id="toggle_undefined"></span>
and there's no unique identifiers/attributes on it, we'll have to locate the right one by using one of the surrounding elements.
Probably what I would use is to find the SPAN by the relative LABEL, e.g.
<label for="Url_option1">Option 1</label>
You can use an XPath like
//label[.='Option 3']//following::span[@id='toggle_undefined']
What this does is finds the LABEL that contains the desired string, 'Option 3', and then finds the first SPAN that follows with the ID 'toggle_undefined'.
If it were me, I would wrap this in a function and pass in the option name I was looking to click, e.g.
public void Toggle(string optionName)
{
Driver.Value.FindElement(By.XPath($"//label[.='{optionName}']//following::span[@id='toggle_undefined']")).Click();
}
and call it like
Toggle("Option 3");
As per the HTML you have shared to invoke click()
on the desired checkbox you can use either of the following solutions:
CssSelector
:
driver.FindElement(By.CssSelector("label[for=Url_Transaction_Out]")).Click();
XPath
:
driver.FindElement(By.XPath("//label[@for='Url_Transaction_Out']")).Click();
To get input with type checkbox just use css selector below.
Element:
<input type="checkbox" data-yesno-name="Url_Transaction_Out" class="url-field-toggle" style="" checked="checked"><span class="glyphicon clickable glyphicon-ok" id="toggle_undefined">
Css Selector:
input[data-yesno-name='Url_Transaction_Out']
Code:
driver.FindElement(By.CssSelector("input[data-yesno-name='Url_Transaction_Out']")).Click();
To check and select:
IWebElement checkbox = driver.FindElement(By.CssSelector("input[data-yesno-name='Url_Transaction_Out']"));
if(!checkbox.IsSelected())
{
checkbox.Click();
}