Skip to content Skip to sidebar Skip to footer

Struts2: Update Second Select Based On First Select Value Using Javascript And Jquery

I am working on a struts2 project where I have 3 html select controls each one being dependent on the previous selection. Say the first select is for country, second for state, thi

Solution 1:

<select id="stateSelect"  name="selectedState" onchange="loadCities(this.value)">
<s:iterator value="#session['myModel'].states" status="itr">
     <option value="<s:property value="code"/>">
      <s:property value="label"/>
</option>
</s:iterator>
</select>

<select id="citySelect"  name="selectedCity" >
</select>

JQuery

functionloadCities(value){

        $("#citySelect").get(0).options.length = 0;
        $("#citySelect").get(0).options[0] = newOption("Loading cities", "-1"); 

        $.ajax({
            type: "POST",
            url: "MyStrutsActionToGetCities",
            data: "{stateID:" + value+ "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#citySelect").get(0).options.length = 0;
                $("#citySelect").get(0).options[0] = newOption("Select city", "-1"); 

                $.each(msg.d, function(index, item) {
                    $("#citySelect").get(0).options[$("#citySelect").get(0).options.length] = newOption(item.Display, item.Value);
                });
            },
            error: function() {
                $("#citySelect").get(0).options.length = 0;
                alert("Failed to load cities");
            }
        });
}

Taken from this tutorial

Update:This example is used to load city list based on the state selected. You can do similar thing to load state list on country selection. Also here is a link describing ajax request/response for struts without using any plugin

Solution 2:

Generally, the way to do this is using the Struts2 JSON plugin which ships with recent versions of Struts2. To interact with jQuery in your JSP you'll want to use s:url to create a URL for your JSON action and then you can invoke it using jQuery's .getJSON() or .load().

However, if your dropdown choices really aren't that complicated, don't over-architect. It can be easier to render them all using s:iterator on the initial page load and use .change() on your dropdown boxes to either move the data between select components, or augment the name attribute on one of the select boxes for the form submit.

Post a Comment for "Struts2: Update Second Select Based On First Select Value Using Javascript And Jquery"