I work with AngularJS and the integrated jQuery library in my project.
I am using the jQuery $.each() function to scroll $.each() my class. I want to create an array of objects from it, as in the following format:
[ {"invoice_no":"value1", "brand":"value2", "model":"value3"}, {"invoice_no":"value1", "brand":"value2", "model":"value3"}, {"invoice_no":"value1", "brand":"value2", "model":"value3"}, {"invoice_no":"value1", "brand":"value2", "model":"value3"}, {"invoice_no":"value1", "brand":"value2", "model":"value3"}, ]
HTML
<div class="panels"> <input class="form-control" name="invoice_no"> <input class="form-control" name="brand"> <input class="form-control" name="model"> </div> <div class="panels"> <input class="form-control" name="invoice_no"> <input class="form-control" name="brand"> <input class="form-control" name="model"> </div> <div class="panels"> <input class="form-control" name="invoice_no"> <input class="form-control" name="brand"> <input class="form-control" name="model"> </div> <div class="panels"> <input class="form-control" name="invoice_no"> <input class="form-control" name="brand"> <input class="form-control" name="model"> </div> <div class="panels"> <input class="form-control" name="invoice_no"> <input class="form-control" name="brand"> <input class="form-control" name="model"> </div>
Js controller
$scope.saveData = function(){ var arrayOFProducts = []; var object = {}; angular.element('.panels').each(function(){ $(this).find('.form-control').each(function(){ var key = $(this).attr('name'); var value = $(this).val(); object [key] = value; }); arrayOFProducts.push(object); }); console.log(arrayOFProducts); }
The main problem is that I get the same values ββfor all json objects inside the array. It seems that only the last input values ββare created as an object, and it pushes it to the array 5 times.
source share