无法使用Jsoup Formelement设置选择选项HTML

时间:2018-07-28 15:31:00

标签: select jsoup option

尝试使用JSOUP fromelement在html中设置选择选项,但没有成功。

<select name="gender" id="gender" class="textfield" required="true">
<option value=""
>Select</option>
<option value="2">Male</option>
<option value="1">Female</option>
<option value="3">Other</option>
</select>

在上述选择选项中设置性别的Jsoup要素:

Element gender = loginForm.select("#gender").first();
        gender.attr("Male","2");

如果有人知道该怎么做,请告诉我,谢谢。

2 个答案:

答案 0 :(得分:0)

您需要设置要选择的选项的selected属性。有关完整示例,请参见以下答案:

Jsoup POST: Defining a selected option to return HTML?

答案 1 :(得分:0)

注释说明:

    String html = "<select name=\"gender\" id=\"gender\" class=\"textfield\" required=\"true\">"
            + "<option value=\"\">Select</option>"
            + "<option value=\"2\">Male</option>"
            + "<option value=\"1\">Female</option>"
            + "<option value=\"3\">Other</option>"
            + "</select>";

    Document doc = Jsoup.parse(html);

    // getting all the options
    Elements options = doc.select("#gender>option");

    // optional, listing of all options
    for (Element option : options) {
        System.out.println("label: " + option.text() + ", value: " + option.attr("value"));
    }

    // optional, find option with attribute "selected" and remove this attribute to
    // deselect it; it's not needed here, but just in case
    Element selectedOption = options.select("[selected]").first();
    if (selectedOption != null) {
        selectedOption.removeAttr("selected");
    }

    // iterating through all the options and selecting the one you want
    for (Element option : options) {
        if (option.text().equals("Male")) {
            option.attr("selected", "selected"); // select only Male
        }
    }

    // result html with selected option:
    System.out.println(doc.body());