Array of jQuery objects

I have an array of objects in a session. It was filled in the selection list. based on the selected item from the list, I would have to pre-populate the form with the attributes of the selected object.

Please, help.

  • Aanu
+3
source share
1 answer

You can store employee information in a javascript object:

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

Then you are attached to the change event in the selection field:

$(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);
        }
    });
});
+12
source

Source: https://habr.com/ru/post/1727388/


All Articles