I would like to get values from the array created inside the each loop
var arr = [];
$.each([52, 97], function(index, value) {
var arr = [value];
});
console.log(arr);
But the logged array has no entry.
I would like to get values from the array created inside the each loop
var arr = [];
$.each([52, 97], function(index, value) {
var arr = [value];
});
console.log(arr);
But the logged array has no entry.
The error what you did is var arr = [ value]; reinitialized variable & wrong setting of array index.
var arr = [];
$.each([52, 97], function(index, value) {
arr[index] = value;
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can also do this with push() as in other answer(@Boris Bresciani).
Your variable arr inside the function is not the same as the outside variable arr, but local to the function. To fix that, do not create a new local variable, but let the function refer to the outside variable instead (this is called a closure). This should work:
var arr =[];
$.each([ 52, 97 ], function( index, value ) {
arr.push(value);
});
console.log(arr);
Add value in Array using each loop in js
var ProductTypeId = [];
$("input[name=ProductTypeId]").each(function() {
if ($(this).prop('checked') == true) {
ProductTypeId.push($(this).val());
}
});
alert(ProductTypeId`enter code here`);
<input type="checkbox" class="custom-control-input" name="ProductTypeId" id="<?php echo $term['productTypeId']; ?>" value="<?php echo $term['productTypeId']; ?>">