Select all options by the text displayed. The text of the option to be selected. Default value is false. If true a partial match on the Options list will be performed, otherwise exact match. When given "Bar" this method would select an option like: <option value="foo">Bar</option>
(string text, bool partialMatch = false)
| 124 | /// <exception cref="ArgumentNullException">If <paramref name="text"/> is <see langword="null"/>.</exception> |
| 125 | /// <exception cref="NoSuchElementException">Thrown if there is no element with the given text present.</exception> |
| 126 | public void SelectByText(string text, bool partialMatch = false) |
| 127 | { |
| 128 | if (text is null) |
| 129 | { |
| 130 | throw new ArgumentNullException(nameof(text), "text must not be null"); |
| 131 | } |
| 132 | |
| 133 | bool matched = false; |
| 134 | ReadOnlyCollection<IWebElement> options; |
| 135 | |
| 136 | if (!partialMatch) |
| 137 | { |
| 138 | // try to find the option via XPATH ... |
| 139 | options = this.WrappedElement.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]")); |
| 140 | } |
| 141 | else |
| 142 | { |
| 143 | options = this.WrappedElement.FindElements(By.XPath(".//option[contains(normalize-space(.), " + EscapeQuotes(text) + ")]")); |
| 144 | } |
| 145 | |
| 146 | foreach (IWebElement option in options) |
| 147 | { |
| 148 | SetSelected(option, true); |
| 149 | if (!this.IsMultiple) |
| 150 | { |
| 151 | return; |
| 152 | } |
| 153 | |
| 154 | matched = true; |
| 155 | } |
| 156 | |
| 157 | if (options.Count == 0 && text.Contains(" ")) |
| 158 | { |
| 159 | string substringWithoutSpace = GetLongestSubstringWithoutSpace(text); |
| 160 | IList<IWebElement> candidates; |
| 161 | if (string.IsNullOrEmpty(substringWithoutSpace)) |
| 162 | { |
| 163 | // hmm, text is either empty or contains only spaces - get all options ... |
| 164 | candidates = this.WrappedElement.FindElements(By.TagName("option")); |
| 165 | } |
| 166 | else |
| 167 | { |
| 168 | // get candidates via XPATH ... |
| 169 | candidates = this.WrappedElement.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]")); |
| 170 | } |
| 171 | |
| 172 | foreach (IWebElement option in candidates) |
| 173 | { |
| 174 | if (text == option.Text) |
| 175 | { |
| 176 | SetSelected(option, true); |
| 177 | if (!this.IsMultiple) |
| 178 | { |
| 179 | return; |
| 180 | } |
| 181 | |
| 182 | matched = true; |
| 183 | } |