Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all Elements in a Form

I would like to use Selenium to submit a form which contains several elements. For example:

<form name="something">
    <input type="text" name="a">Username</input>
    <input type="password" name="b">password</input>
    <select name="c" id="c">
       <option value="1">1</option>
       <option value="2">2</option>
    </select>
    <input type="submit" name="submit">submit</input>
</form>

If I use find.Element(By.name) to find out the form element, how can I get its children elements a, b, and c? And input the values into these three elements then submit the form?

Another similar question is: if I get the element a, how to get elements b and c are in the same form and to fill (or select) values first, then submit the form?

Thanks in advance!

like image 863
Eve Avatar asked Nov 22 '13 15:11

Eve


People also ask

How do you get all elements in a form?

Getting all of the elements in a form # You can get all of the elements in the form by getting the form itself, and then calling the elements property on it. var form = document. querySelector('#my-form'); var elements = form.

Which property is used to return all form elements?

The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the <form> element.

How do you access the elements of a form using objects?

The Form Object in HTML DOM is used to represent the HTML < form > element. This tag is used to set or get the properties of < form > element. This element can be accessed by using getElementById() method.


1 Answers

You can use xpath to get all direct child elements of a specific element using parent/*.

If you already have your form element using findElement(), as below:

WebElement formElement = driver.findElement(By.name("something"));
List<WebElement> allFormChildElements = formElement.findElements(By.xpath("*"));

or directly using:

List<WebElement> allFormChildElements = driver.findElements(By.xpath("//form[@name='something']/*"));

Then look at the tag and type of each element to specify its value:

for (WebElement item : allFormChildElements)
{
    if (item.getTagName().equals("input"))
    {
        switch (item.getAttribute("type"))
        {
            case "text": 
                //specify text value
                break;
            case "checkbox":
                //check or uncheck
                break;
            //and so on
        }
    }
    else if (item.getTagName().equals("select"))
    {
        //select an item from the select list 
    }  
}
like image 87
Faiz Avatar answered Nov 02 '22 23:11

Faiz