Reputation: 397
Unable to print fields value. Throws "Cannot read property 'push' of undefined" error
My component.html
<div class="checkbox abc-checkbox abc-checkbox-success">
<input class="inputChk" value="Serial_Number" id="ser_num" type="checkbox" checked="true">
<label for="Serial_Number">Serial Number</label>
</div>
<div class="checkbox abc-checkbox abc-checkbox-success">
<input class="inputChk" value="Stock_Number" id="stk_num" type="checkbox" checked="true">
<label for="Stock_Number">Customer Stock Number</label>
</div>
<button type="button" class="btn btn-primary" (click)="submitCheckedValues()">Submit</button>
My component.ts
export class Sample{
fields: String[] = [];
submitCheckedValues(){
$('input:checkbox.inputChk').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
//printing sThisVal;
if(sThisVal){
this.fields.push(sThisVal);
}
});
console.log(this.fields);
}
Upvotes: 0
Views: 125
Reputation: 5522
I want to give another solution if you want to try
$.each([1, 2, 3], (function(i, e) {
console.log(this);
}).bind(this));
You can bind each function with this after that you can access this inside each.
Upvotes: 0
Reputation: 23859
There is this error because this.fields
is not pointing to the fields
property of the class. this
refers to the scope of the anonymous function instead.
You need to save the reference in a local variable before executing the code:
submitCheckedValues(){
let self = this; // Store the reference
$('input:checkbox.inputChk').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
//printing sThisVal;
if(sThisVal){
self.fields.push(sThisVal); // Use the reference of self here
}
});
console.log(this.fields);
}
Upvotes: 5