Aanu
Aanu

Reputation: 4219

Jquery array of objects

I have an array of objects in session. This has been populated in select list. based on the selected item from the list, I would have to pre-populate the form with the attributes of the object selected.

Please help.

Upvotes: 4

Views: 51806

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could store employee information into a javascript object:

var employees = [
    { id: '1', sex: 'm', city: 'Paris' }, 
    { id: '2', sex: 'f', city: 'London' },
    ... etc fill this in a foreach loop
];

Next you bind to the change event of the select box:

$(function()
{
    $('select#id_of_the_employees_select').change(function(e) {
        // Get the current selected employee id
        var selectedEmployeeId = $(this).val();
        // find the corresponding employee in the list
        var emps = $.grep(employees, function(n, i) {
            return n.id == selectedEmployeeId;
        });
        if (emps.length > 0) {
            var employee = emps[0];
            // fill the form elements with employee data:
            $('#employee_sex').val(employee.sex);
            $('#employee_city').val(employee.city);
        }
    });
});

Upvotes: 16

Related Questions