Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery array of objects

Tags:

jquery

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.

  • Aanu
like image 991
Aanu Avatar asked Jan 05 '10 17:01

Aanu


People also ask

How do I iterate an array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can you have an array of objects in JavaScript?

Array Elements Can Be Objects JavaScript variables can be objects.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

How do I create an array in jQuery?

Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.


1 Answers

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);
        }
    });
});
like image 60
Darin Dimitrov Avatar answered Oct 25 '22 12:10

Darin Dimitrov