How to select options from custom dropdown where the options will be filter as per your input text

How to select options from a dropdown that contains dynamic options, and it will be filtered as per your input text

1 Like

If you have a <select> tag, then maybe you can use the selectOptionByLabel with the boolean set as true, which allows you to use RegEx (Regular Expression).
WebUI.selectOptionByLabel(findTestObject(‘…’), “.*regex input text.*”, true)

With RegEx, then you only need part of your input text along with wildcards and/or comparison options, like: \\d{1,4} or \\s. I think this depends on how much you know about your filtered input text, though, and if the RegEx returns one or more texts–the command can succeed when only one text is selected.

If you do not have a <select> tag, then you may have to use a method such as getting a cell in a web table. Again, to make your comparison, use a statement that allows the use of RegEx, like: WebUI.verifyMatch(findTestObject(‘…’), “regex input text.*”, true).

For a “custom” / dynamic dropdown in Katalon, the approach depends on whether it is a real <select> element or a fully custom HTML list.​

If it is a real <select>

You can let Katalon do the filtering for you using regex in selectOptionByLabel:

WebUI.selectOptionByLabel(
    findTestObject('path/to/select_object'),
    '.*your partial text.*',
    true   // use regular expression
)
  • The third argument true enables regex, so the option whose label matches the pattern will be selected.​
  • Adjust the pattern to match your filtered text, for example ".*London.*".

If it is a custom dropdown (no <select> tag)

For a fully custom dropdown, you generally do:

  1. Click to open the dropdown.
  2. Type into the input that filters options.
  3. Locate the resulting option in the list and click it.

Example:

// 1. Open dropdown
WebUI.click(findTestObject('page/dropdown_button'))

// 2. Type filter text
WebUI.setText(findTestObject('page/dropdown_filter_input'), 'your text')

// 3. Wait for filtered options to appear
WebUI.waitForElementVisible(findTestObject('page/dropdown_option_dynamic'), 10)

// 4. Click the desired option (can also parametrize or use regex in XPath)
WebUI.click(findTestObject('page/dropdown_option_dynamic'))

If you must validate which option is shown/selected, use keywords that support regex in verification, such as:

WebUI.verifyMatch(
    WebUI.getText(findTestObject('page/selected_option_label')),
    '.*your partial text.*',
    true
)

This mirrors the advice to use regex for matching dynamic option text when selectOptionByLabel is not usable.

This implies that your dropdown list would be really a custom one, not a plain old HTML <select><option>.... It would involve JavaScript functions.

We need to see the way how your dropdown list is implemented. We would need to see the HTML source and the JavaScript source. Preferably, we would need to get access to your web page’s URL in action. Otherwise, we would never be able to answer to your question.

I made a demonstration and published it at


This is a small Katalon Studio project for demonstration purpose.
This project provides a reference implementation that concerns a topic raised in the Katalon user forum at

where the original poster asked:

How to select options from a dropdown that contains dynamic options, and it will be filtered as per your input text

I made the following codes:

  1. an HTML that displays a button and a dropdown list => page.html
  2. a JavaScript that controls the interactions on the page => script.js
  3. a Katalon TestCase script that mimics a human operation on the page => TC1

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
                   initial-scale=1.0">
    <title>
        Document
    </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="dropdown m-4">
        <button class="btn btn-secondary
                       dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown"
            aria-expanded="false">
            Dropdown button
        </button>
        <ul class="dropdown-menu pt-0" aria-labelledby="dropdownMenuButton1">
            <input type="text" class="form-control
                          border-0 border-bottom
                          shadow-none mb-2" placeholder="Search..." oninput="handleInput()">
        </ul>
    </div>
    <p id="selectedValue" class="m-4">
        Selected Value: <span id="valueDisplay"></span>
    </p>

    <script src="./script.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js">

    </script>
</body>

</html>

JavaScript:

const handleInput = () => {
    const inputValue =
        document
            .querySelector('.form-control').value;
    const results =
        ["apple", "banana", "cherry",
            "date", "elderberry"];
    const parentElement =
        document
            .querySelector(".dropdown-menu");
    const elementsToRemove =
        document.querySelectorAll("li");
    elementsToRemove.forEach(element => {
        element.remove();
    });
    if (inputValue) {
        const matchingWords =
            results
                .filter(word => word
                    .includes(inputValue));
        matchingWords.sort((a, b) => {
            const indexA =
                a.indexOf(inputValue);
            const indexB =
                b.indexOf(inputValue);
            return indexA - indexB;
        });
        matchingWords.forEach(word => {
            const listItem =
                document.createElement("li");
            const link =
                document.createElement("a");
            link.classList.add("dropdown-item");
            link.href = "#";
            link.textContent = word;
            link.onclick = handleSelection;
            listItem.appendChild(link);
            parentElement.appendChild(listItem);
        });
        if (matchingWords.length == 0) {
            const listItem =
                document.createElement('li');
            listItem.textContent = "No Item";
            listItem.classList.add('dropdown-item');
            parentElement.appendChild(listItem);
        }
    } else {
        results.forEach(word => {
            const listItem =
                document.createElement("li");
            const link =
                document.createElement("a");
            link.classList.add("dropdown-item");
            link.href = "#";
            link.textContent = word;
            link.onclick = handleSelection;
            listItem.appendChild(link);
            parentElement.appendChild(listItem);
        });
    }
}
const handleSelection = (event) => {
    console.log(event)
    event.preventDefault();
    if (event.type === 'click') {
        const selectedValue =
            event.target.firstChild.textContent;
        document
            .getElementById('valueDisplay')
            .textContent = selectedValue;
    }
}

handleInput();

Test Case:

import java.nio.file.Path
import java.nio.file.Paths

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import org.openqa.selenium.Keys as Keys

TestObject makeTestObject(String id, String xpath) {
	TestObject tObj = new TestObject(id)
	tObj.addProperty("xpath", ConditionType.EQUALS, xpath)
	return tObj	
}

Path projectDir = Paths.get(RunConfiguration.getProjectDir())
Path html = projectDir.resolve("./page.html")
String url = html.toFile().toURI().toURL().toExternalForm()

// open the page
WebUI.openBrowser('')
//WebUI.maximizeWindow()
WebUI.setViewPortSize(800, 600)
WebUI.navigateToUrl(url)

// click the button
TestObject button = makeTestObject("button", "//button[@id='dropdownMenuButton1']")
WebUI.click(button)

// make sure the input field is present
TestObject inputField = makeTestObject("inputField", "//input[@type='text']")
WebUI.verifyElementPresent(inputField, 10)
WebUI.delay(3)

// type a text 'ba' into the input field
WebUI.sendKeys(inputField, "ba")

//  click the 1st <li> element
li1 = makeTestObject("li", "//ul/li[1]")
WebUI.verifyElementPresent(li1, 10)
WebUI.click(li1)

// verify if the input field is filed with "banana"
TestObject valueDisplay = makeTestObject("valueDisplay", "//*[@id='valueDisplay']")
assert WebUI.getText(valueDisplay) == "banana"

WebUI.closeBrowser() 

I refered to the following article for the sample HTML and JavaScript code that implements a custom dropdown list with filtering feature:

How to activate the demonstration

In Katalon Studio (any version will do), open this project and just run the “Test Cases/TC1”

How the demo works

The TC1 opens a browser (Chrome as default) window. In the browser, the page.html is displayed.

The TC1 mimics human interaction. Firstly, the TC1 clicks the button labeled “Dropdown button”. Then a dropdown list will be displayed.

The TC1 types a string “ba” into the text input field. Then the page filters the dropdown list and show the enteries that match with the typed string.

The TC1 clicks the 1st entry of the list. Effectively, the “banana” will be clicked.

The page acknowledges that human clicked the “banana” entry, and the page shows “Selected Value: banana”.

The TC1 makes an assertion that the “Selected Value” should be “banana”.

As the screenshot shows, the test passed as expected.

Conclusion

This sample project demonstrates a HTML page with custom dropdown list that filters items by input text. Also this project shows a sample Test Case scriptipt that can interacte with the page.

Now, does this sample solve the problem of the original poster? — No, it will not. The original poster’s target page will be completely different from my sample page. Therefore copy&pasting my code makes no sense for the original poster. He/she has to invent a solution for his/her own target web page.

I developed this sample project to show what sort of concrete information you need to disclose when you ask others for help for test coding. We need to see the HTML and JavaScript source in order to develop a test case script.

@JP_FLT

Have you checked the HTML and JavaScript source of your target?

1 Like

Ideally, for such dropdowns, the options tag might not be present, but the list of options will have an

  • tag.

    So you need to create your element accordingly.

    Then set the text (‘text_to_search’) in your search field using

    WebUI.setText(findTestObject(‘your_search_field’), text_to_search)

    Also in some applications, the list does not come up directly so you would have to wait for the results to show up and for that what I did was check the attribute value of the search field as below

    WebUI.verifyElementAttributeValue(object, ‘value’, ‘text_to_search‘, 0)

    Also create a parameterized locator which will contain the exact text that you would want to select. Why might you need this? - Let’s say it is country dropdown and you enter “In” in the field it will give multiple options now to select your expected country (let’s say “India“) you might need this.

    This will help you if you want to test for multiple test data.

    The xpath could be (you can modify as per your element)

    //*[text()[contains(.,‘${exact_name}’)]]

    Then click on that parameterized element

    WebUI.click(findTestObject(‘path_to_parameterized_object’, [(‘exact_name’) : exact_name]))

    Then validate that the selected name is appearing in the dropdown as a value.

  • Hi @JP_FLT,

    Any of above replies answer you? If yes, please help mark them as solution. If no, let us know more about your opinion. Thank you