Reputation: 111
I'm trying to get the text value of checkbox label. Here is an HTML code
<div id="content" class="large-12 columns">
<div class="example">
<h3>Checkboxes</h3>
<form id='checkboxes'>
<input type="checkbox"> checkbox 1</br>
<input type="checkbox" checked> checkbox 2
</form>
</div>
So What I have tried so far
Driver.FindElement(By.XPath("//input[@type='checkbox']")).Text
;Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("value");
Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("name");
Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("innerText");
Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("innerHTML");
All this attempts return ""
.
Any ideas how to get it or Javascript is my only option ?
Upvotes: 1
Views: 2041
Reputation: 117
You can also use CSS Selector to get the checkbox label:
Element CheckBox = Driver.FindElement(By.CssSelector("input[type='checkbox']"));
string firstChkBoxTxt = CheckBox.FirstOrDefault().GetAttribute("innerText");
string secondChkBoxTxt = CheckBox.LastOrDefault().GetAttribute("innerText");
Upvotes: 0
Reputation: 910
You can try following to get the required text from the two checkboxes:
Driver.FindElement(By.XPath("//form[@id='checkboxes']/input[@type='checkbox'][1]")).Text
Driver.FindElement(By.XPath("//form[@id='checkboxes']/input[@type='checkbox'][2]")).Text
Let me know, if above code does not work for you.
Upvotes: 0
Reputation: 6683
The xpath for a text following an input tag is //input[1]/following-sibling::text()[1]
but there are serious limitations for Selenium to run expressions like this. It only can handle tag elements. Try to get the parent and retrieve texts from there.
string[] texts = Driver.FindElement(By.XPath("//form[@id='checkboxes']"))
.GetAttribute("innerText")
.Split("\r\n".ToCharArray()
);
Then texts[0] returns:
checkbox 1
Upvotes: 1
Reputation: 11
Add an class or id attribute to the checkboxes and then try to find the element by css selector like: Driver.FindElement(By.CssSelector(""))
Upvotes: 0