Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Htmlunit get form input by ID instead of name

Tags:

java

htmlunit

I have a form that has multiple rows and similar inputs. They have different IDs but the same name.

<input id="E2EMPL1" class="uppercase required" type="text" value="" maxlength="9" size="9" name="E2EMPL">

<input id="E2EMPL2" class="uppercase required" type="text" value="" maxlength="9" size="9" name="E2EMPL">

I can fill in the first row, no problem, but when it comes to filling in the 2nd row, I can't figure it out.

This is to fill out the first row:

            HtmlPage mainPage = webClient.getPage(siteName);
            form = mainPage.getFormByName("timeForm");

            for (TimeEntry te: aList){
               form.getInputByName("chkaction").setValueAttribute("checked");
               form.getInputByName("E2EMPL").setValueAttribute(te.getResource());
               form.getInputByName("ww_fE2WKDT").setValueAttribute(te.getEntryDate());
            }

But I'm not sure how to fill out the 2nd row when the name stays the same, but the ID changes to EMPL1, EMPL2, etc. I think I'm suppose to use xpath but I'm not sure how?

form.getByXPath("//input[@id='E2EMPL2']"); ???

Edit: As a side note. I have tried with HTTPClient to just POST the data. Unfortunately, it doesn't work for this form, and I have no idea why. I've asked a question on here that never got any answers and don't have enough rep to put a good bounty on it. However, I just gave HTMLUnit a try and if I fill in the form, and hit the submit button, it will work just fine. This is why I don't use HTTPClient.

If anybody wants to see the question, I deleted it, but I'll undelete it if anybody really wants to see it.

The HTML form has 5 rows of data, and it's a little slow to fill one row, click submit 5 times vs fill the 5 rows and then click submit. I was hoping it'd be a little faster, but if it's impossible to do this, I'll give up on this. I was hoping some people could have an insight.

like image 647
arsarc Avatar asked May 25 '16 16:05

arsarc


2 Answers

Try this:

HtmlForm Form = htmlPage.getHtmlElementById("form id");
like image 145
OPfan Avatar answered Sep 28 '22 08:09

OPfan


You can get the element as a DomElement (instead of an InputElement) and set its value attribute:

HtmlPage mainPage = webClient.getPage(siteName);

DomElement e2empl1 = mainPage.getElementById("E2EMPL1");
if (e2empl1.getTagName().toLowerCase().equals("input")) {
    e2empl1.setAttribute("value", "value1");
}

DomElement e2empl2 = mainPage.getElementById("E2EMPL2");
if (e2empl2.getTagName().toLowerCase().equals("input")) {
    e2empl2.setAttribute("value", "value2");
}

(Maybe you can skip the tagname check)

like image 41
Manuel Domínguez Avatar answered Sep 28 '22 09:09

Manuel Domínguez