2

Trying to set select option in html using JSOUP fromelement but isn't working out.

<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 formelement for setting gender in above select option:

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

If anyone know how to do this, please let me know, thank you.

aynber
  • 22,380
  • 8
  • 50
  • 63

2 Answers2

0

You need to set the selected attribute of the option you want to pick. See this answer for a complete example:

Jsoup POST: Defining a selected option to return HTML?

Joe W
  • 2,773
  • 15
  • 35
0

Explanation in comments:

    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());
Krystian G
  • 2,842
  • 3
  • 11
  • 25