vuis vuis - 2 months ago 5
Javascript Question

Spring populating form fields based on value from select box

I have select box where I select name of employee from list of all employees. What I want to achieve is to get other attributes of object employee. I use javascript to achieve it but I always get the first element from the list (index 0). Here is the code:

<sf:select path="employee" onchange="change()" >
<sf:option value="">
Choose employee
</sf:option>
<sf:options itemLabel="employeeName" items="${employeeList}"
itemValue="employeeId" />
</sf:select>

<input id="licenseNr"/>


And javascript:

<script>
function change(){
var comboIndex = document.getElementById("employee").value;
document.getElementById("licenseNr").value=("${employeeList.get(comboIndex).licenseNr}");
}
</script>

Answer

I have solved problem by adding parameter in url with jquery

$(function() {
        $("#employee")
                .change(
                        function(e) {
                            var option = $(this).val();                             
                            var newUrl = "someUrl?id="+option;
                            window.location=newUrl;                             
                        });
    });

In controller I have added RequestParam annotation

@RequestMapping(value = "/someUrl", method = RequestMethod.GET)
public String showForm(@RequestParam(required = false, defaultValue="-1")
 Integer id,Model model){
if(id>0){   
    Employee employee = service.fetchEmployeeById(id);      
                model.addAttribute("employee", employee);}
    return "someUrl";}

Then I have added value to text field

<input id="licenseNr" value="${employee.licenseNr}" />  
Comments