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.
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.
Array Elements Can Be Objects JavaScript variables can be 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' }] };
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.
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With