Home > OS >  How to alert Checkbox Records id values on form submission in angular
How to alert Checkbox Records id values on form submission in angular

Time:02-23

The Code below successfully display records in a checkbox via angular 13

Here is my issue and what am now trying to achieve:

I want to print or alert all the selected checkbox records id's as seperated by comma on form submission

Eg. if I select and check First and second records/language, I should be able to alert their ids eg 100,200

Eg. If I check first 3 records, I should be able to alert their id's 100,200,300 on form submission.

but when I click on submit button, nothing is alerted

here is app.component.html

<div >
    <h1 >Learners Languages Checkbox </h1>

    <div >
 


<div *ngFor="let lang of langsdata; let i=index;">
                    <input [(ngModel)]="langsdata[i].checked" type='checkbox' value="{{lang.id}}">{{ lang.id }} {{ lang.lg }} 
                </div>


            <br>
            Selected items : {{ selectedlang }}

   </div>
   <button type="submit"  (ngSubmit)="onSubmit()">Submit</button>

  </div>

here is app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, FormArray} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent implements OnInit {
        
langsdata: any = [
{"id":100,"lg": "Nodejs"},
{"id":200,"lg": "PHP"},
{"id":300,"lg": "vuejs"},
{"id":400,"lg": "AngularJS"}
];

languages: [];
selectedlang: "";

registerForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {
  }

  onSubmit(){
    // var myFormData = new FormData();
  //alert(this.registerForm.value.languages)
      this.selectedlang = "";

//print or alert selected language ids  eg 100,200,300 based on checkedbox records
    alert(this.langsdata);
  }

   

     


 ngOnInit(): void {
  }


     
}

CodePudding user response:

Please check the example: https://stackblitz.com/edit/angular-formbuilder-v15y3w

I've added new key in your languages objects, since you were trying to use checked and it didn't exist on them. Like: { id: 100, lg: 'Nodejs', checked: false }.

Then I only had to introduce an array (since it's more readable pushing to array than concatenating a string) and that's bascily it:

this.langsdata.forEach((lang) => {
    if (lang.checked) {
        this.selectedLangs.push(lang.id);
    }
});
this.selectedLangsString = this.selectedLangs.toString();

Some changes in html too, like (click) instead of (ngSubmit), but see for yourself and tell me if it works for you.

  • Related